pyplot+pandas实现操作excel及画图

1、安装jupyter lab

pip install jupyterlab

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

jupyter lab

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

2、安装依赖

pip install matplotlib

pip install xlrd

pip install pandas

3、读取excel

复制代码
import pandas as pd

df = pd.read_excel('his.xls')


# 读取列名
for i in df.columns:
    print(i)

df.columns[0]


# 读取指定sheet 名
filePath = 'his.xlsx'
df = pd.read_excel(r'his.xlsx', sheet_name=1)

# 场景2:excel 中第 2 行才是我们想要的标题(即:header=1)
df = pd.read_excel(filePath, header=1)

# 读取 Excel,指定索引列
df= pd.read_excel(filePath, index_col='ID')

# 读取前 3 行数据(默认 5 行)
print(df.head(3))

# 读取后 3 行数据(默认 5 行)
print(df.tail(3))

# 数据筛选
# 读取第一列所有数据
df.iloc[:, 0]

遍历所有sheet

复制代码
import pandas as pd
excel_file = pd.ExcelFile('his.xls')

for sheet_name in excel_file.sheet_names:
    print(sheet_name) 
    df = excel_file.parse(sheet_name)
    print(df.columns)

4、画图

多个子图

复制代码
import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt 

# 从上一步得到excel的列
columns = df.columns
size = columns.size

#新建一个画布
fig = plt.figure()  

# 设置多行 一列的表格 figsize 用于设置画布大小  是否共享x轴坐标值 sharex
f, ax = plt.subplots(size, 1, figsize=(10,30), sharex= True, sharey=False) 


for i in range(size):
    # 将每一列数据作为一个表格,用于绘制,如果是多列,则ax[i:xx]
    ax[i].plot(df.iloc[:, i])
    ax[i].set_title(columns[i])

plt.show()

多组数据一组图

复制代码
# c='black' 设置线条颜色
ax[0].plot(df.iloc[:, 0])
ax[0].plot(df.iloc[:, 1])
相关推荐
jiayong23几秒前
Spring AI Alibaba 深度解析(一):框架概述与核心功能
java·人工智能·spring
亚马逊云开发者16 分钟前
基于Amazon Q Developer实现IoT设备的Amazon Timestream性能与成本优化
人工智能
cyyt19 分钟前
深度学习周报(12.15~12.21)
人工智能·深度学习·最优传输
Blossom.11819 分钟前
大模型推理优化实战:连续批处理与PagedAttention性能提升300%
大数据·人工智能·python·神经网络·算法·机器学习·php
陈天伟教授23 分钟前
人工智能训练师认证教程(1)数据标注-Labelimg的使用教程
人工智能·神经网络·机器学习
Hcoco_me29 分钟前
Seq2Seq:Encoder-Decoder架构详解
人工智能·rnn·深度学习
江上鹤.14836 分钟前
Day44 训练和测试的规范写法
人工智能·深度学习·机器学习
Spring AI学习1 小时前
Spring AI深度解析(11/50):异常处理与容错机制实战
java·人工智能·spring
木头左1 小时前
结合基本面分析的LSTM量化交易模型入参设计原则
人工智能·rnn·lstm
HuggingFace1 小时前
流式数据集:效率提升 100 倍!
人工智能