Python加载多层表头DataFrame实现整流器电压电流与日期关联绘图
最优实现方案
你当前拆分单整流器DataFrame存入字典的方案不利于后续批量处理、筛选和绘图,更推荐将数据转换为**长格式(tidy data)**存储,所有记录统一放在同一个DataFrame中,仅保留「整流器ID」「采集日期」「电压」「电流」4个核心字段,后续所有操作都可以通过pandas原生的筛选、分组功能实现,效率更高。
第一步:数据结构重塑
import pandas as pd import matplotlib.pyplot as plt # 原读取逻辑不变 df = pd.read_excel("Rectifier_DB.xlsx", header = [0,1], index_col=0) # 为两级列索引命名,方便后续转换 df.columns.names = ['采集日期', '参数'] # 将多级列索引转为行,生成长格式表 df_long = df.stack(level='采集日期').reset_index() # 重命名列名更符合使用习惯 df_long = df_long.rename(columns={ 'level_0': '整流器ID', 'Volts': '电压(V)', 'Amps': '电流(A)' }) # 将日期列转为datetime格式,绘图时X轴会自动排序、格式化 df_long['采集日期'] = pd.to_datetime(df_long['采集日期'], format='%d/%m/%Y')
第二步:常用绘图场景实现
场景1:单个整流器电压电流随时间变化曲线
# 指定要查询的整流器ID target_id = '9E220ECP5001' plot_data = df_long[df_long['整流器ID'] == target_id].sort_values('采集日期') # 双Y轴分别绘制电压、电流 fig, ax1 = plt.subplots(figsize=(10, 5)) # 左轴:电压 color = 'tab:red' ax1.set_xlabel('采集日期') ax1.set_ylabel('电压(V)', color=color) ax1.plot(plot_data['采集日期'], plot_data['电压(V)'], color=color, marker='o', label='电压') ax1.tick_params(axis='y', labelcolor=color) # 右轴:电流 ax2 = ax1.twinx() color = 'tab:blue' ax2.set_ylabel('电流(A)', color=color) ax2.plot(plot_data['采集日期'], plot_data['电流(A)'], color=color, marker='s', label='电流') ax2.tick_params(axis='y', labelcolor=color) plt.title(f'整流器{target_id}运行趋势') fig.tight_layout() plt.show()
场景2:批量生成所有整流器的趋势图
直接用pandas分组功能遍历所有整流器,比遍历字典更灵活:
for rect_id, data_group in df_long.groupby('整流器ID'): data_group = data_group.sort_values('采集日期') plt.figure(figsize=(10,5)) plt.plot(data_group['采集日期'], data_group['电压(V)'], marker='o', label='电压(V)') plt.plot(data_group['采集日期'], data_group['电流(A)'], marker='s', label='电流(A)') plt.title(f'整流器{rect_id}运行趋势') plt.xlabel('采集日期') plt.legend() plt.tight_layout() # 可直接保存到本地 plt.savefig(f'./{rect_id}_运行趋势.png') plt.close()
方案优势
相比拆分字典的方案,长格式结构的优点:
- 无需维护多份独立DataFrame,内存占用更低
- 可直接使用pandas原生的分组、聚合函数做批量统计,比如计算所有整流器的季度平均电压等
- 跨设备对比更方便,如需对比多个整流器的电压趋势,仅需一次筛选即可拿到所有需要的数据
内容的提问来源于stack exchange,提问作者Jhangir Awan
相关产品推荐
相关产品推荐

