You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何转换宽格式pandas dataframe用matplotlib绘制A1行的LP%数据

完整实现代码
import pandas as pd
import matplotlib.pyplot as plt

# 构造示例DataFrame
data = {'RowName': ['A1', 'A2', 'A3'], '20/09/21 (LP%)': [120, 0, 0], '20/09/21 (Vol)': [13, 1, 31], '20/09/21 (OI)': [0, 0, 0], '21/09/21 (LP%)': [135.0, 143.43, 143.43], '21/09/21 (Vol)': [68.6, 63.81, 58.1], '21/09/21 (OI)': [0, 0, 0], '22/09/21 (LP%)': [130, 0, 0], '22/09/21 (Vol)': [0, 0, 0], '22/09/21 (OI)': [75, 80, 85]}
df = pd.DataFrame(data)

# 1. 筛选列名包含(LP%)的目标列
df_lp = df.filter(regex='LP%')
# 2. 提取行名为A1对应的数值作为Y轴数据
y_values = df_lp[df['RowName'] == 'A1'].values.flatten()
# 3. 提取列名中的日期作为X轴刻度
x_ticks = [col.split(' ')[0] for col in df_lp.columns]

# 绘图设置
plt.figure(figsize=(7, 4))
# 绘制折线图,添加标记点
plt.plot(x_ticks, y_values, marker='o', color='#2c7fb8', linewidth=2)
# 设置坐标轴与标题
plt.xlabel('日期', fontsize=11)
plt.ylabel('LP (%)', fontsize=11)
plt.title('A1对应LP%趋势变化', fontsize=13)
# 添加网格增强可读性
plt.grid(alpha=0.3, linestyle='--')
# 自动调整布局避免标签被截断
plt.tight_layout()
plt.show()
关键步骤说明
  • 筛选目标列:通过filter(regex='LP%')直接匹配所有列名包含LP%的列,无需手动枚举
  • 提取A1行数据:先通过df['RowName'] == 'A1'筛选出A1对应的行,再用flatten()将二维数组转为一维数组适配matplotlib输入要求
  • 提取X轴刻度:对每个列名按空格切割,取第一部分即可得到纯日期字符串作为X轴刻度值
  • 绘图参数可根据需要调整:比如marker修改标记样式、color修改线条颜色、figsize调整画布大小等

内容的提问来源于stack exchange,提问作者Sylv99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:54:05