当前位置:   article > 正文

pyplot+pandas实现操作excel及画图

pyplot+pandas实现操作excel及画图

1、安装jupyter lab

pip install  jupyterlab

# 启动 建议在指定的项目文件夹下 开启cmd窗口并执行

jupyter lab

启动后会自动打开浏览器访问

2、安装依赖

pip install matplotlib
pip install xlrd
pip install pandas

3、读取excel

  1. import pandas as pd
  2. df = pd.read_excel('his.xls')
  3. # 读取列名
  4. for i in df.columns:
  5. print(i)
  6. df.columns[0]
  7. # 读取指定sheet 名
  8. filePath = 'his.xlsx'
  9. df = pd.read_excel(r'his.xlsx', sheet_name=1)
  10. # 场景2:excel 中第 2 行才是我们想要的标题(即:header=1
  11. df = pd.read_excel(filePath, header=1)
  12. # 读取 Excel,指定索引列
  13. df= pd.read_excel(filePath, index_col='ID')
  14. # 读取前 3 行数据(默认 5 行)
  15. print(df.head(3))
  16. # 读取后 3 行数据(默认 5 行)
  17. print(df.tail(3))
  18. # 数据筛选
  19. # 读取第一列所有数据
  20. df.iloc[:, 0]

4、画图

多个子图

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. # 从上一步得到excel的列
  5. columns = df.columns
  6. size = columns.size
  7. #新建一个画布
  8. fig = plt.figure()
  9. # 设置多行 一列的表格 figsize 用于设置画布大小 是否共享x轴坐标值 sharex
  10. f, ax = plt.subplots(size, 1, figsize=(10,30), sharex= True, sharey=False)
  11. for i in range(size):
  12. # 将每一列数据作为一个表格,用于绘制,如果是多列,则ax[i:xx]
  13. ax[i].plot(df.iloc[:, i])
  14. ax[i].set_title(columns[i])
  15. plt.show()

多组数据一组图

  1. # c='black' 设置线条颜色
  2. ax[0].plot(df.iloc[:, 0])
  3. ax[0].plot(df.iloc[:, 1])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/418199
推荐阅读
相关标签
  

闽ICP备14008679号