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])
相关推荐
飞哥数智坊7 小时前
GPT-5-Codex 发布,Codex 正在取代 Claude
人工智能·ai编程
倔强青铜三7 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
虫无涯8 小时前
Dify Agent + AntV 实战:从 0 到 1 打造数据可视化解决方案
人工智能
Dm_dotnet10 小时前
公益站Agent Router注册送200刀额度竟然是真的
人工智能
算家计算10 小时前
7B参数拿下30个世界第一!Hunyuan-MT-7B本地部署教程:腾讯混元开源业界首个翻译集成模型
人工智能·开源
机器之心10 小时前
LLM开源2.0大洗牌:60个出局,39个上桌,AI Coding疯魔,TensorFlow已死
人工智能·openai
Juchecar11 小时前
交叉熵:深度学习中最常用的损失函数
人工智能
林木森ai11 小时前
爆款AI动物运动会视频,用Coze(扣子)一键搞定全流程(附保姆级拆解)
人工智能·aigc
聚客AI12 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
BeerBear14 小时前
【保姆级教程-从0开始开发MCP服务器】一、MCP学习压根没有你想象得那么难!.md
人工智能·mcp