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

Pandas循环访问列名:批量绘制指定列图表的实现方案

解决Pandas自动选择列绘图的问题(排除指定列/按列位置选择)

我来帮你搞定这两个绘图列选择的问题,先从你遇到的第一个错误说起:

一、自动排除指定列,绘制剩余所有列

你之前的代码里,获取要绘图的列这一步写错了——df.columns.value_counts().drop(['year'],['Date'],['month'])有两个明显问题:

  • drop方法只接受一个列名列表参数,不能传多个单独的列表
  • 完全没必要用value_counts(),直接操作df.columns就能得到所有列名

修正后的代码如下,核心是先定义要排除的列,再筛选出剩余列:

import matplotlib.pyplot as plt
from matplotlib import dates as mdates
import pandas as pd

# 假设你的df已经加载完成,可选:提前处理NaN值让曲线更连续
# df = df.fillna(method='ffill')

fig, ax = plt.subplots(figsize=(10, 2))

# 定义要排除的列
exclude_cols = ['Date', 'year', 'month']
# 筛选出所有需要绘图的列:总列名减去排除的列
plot_cols = [col for col in df.columns if col not in exclude_cols]

# 循环绘制所有目标列
for col in plot_cols:
    ax.plot(df['Date'], df[col], label=col)

# 以下是原代码的日期格式化逻辑,保持不变
years = mdates.YearLocator() 
months = mdates.MonthLocator() 
years_fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

这样就会自动绘制除了Date、year、month之外的所有列,不用手动逐个列名。

二、按列位置选择指定列绘图

如果想按列的位置(比如你说的第1、3、4列,对应Biscuits、Candies、Honey)来选择,要注意Pandas的列索引是从0开始的:你说的第1列对应索引1,第3列对应索引3,第4列对应索引4。可以直接通过列索引获取列名:

通用解决方案代码:

import matplotlib.pyplot as plt
from matplotlib import dates as mdates
import pandas as pd

# 假设你的df已经加载完成
fig, ax = plt.subplots(figsize=(10, 2))

# 指定要选择的列位置(0索引,对应你说的第1、3、4列)
col_positions = [1, 3, 4]
# 通过索引获取目标列名列表
plot_cols = df.columns[col_positions].tolist()

# 循环绘制指定列
for col in plot_cols:
    ax.plot(df['Date'], df[col], label=col)

# 日期格式化逻辑保持不变
years = mdates.YearLocator() 
months = mdates.MonthLocator() 
years_fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plt.show()

如果你的列位置是从1开始计数的,只需要把col_positions里的每个数减1就行,比如你说的第1、3、4列(1开始)对应[0,2,3](0开始)。

额外提醒

你的数据里Candies列有NAN值,matplotlib绘图时会自动跳过这些缺失值,但如果需要让曲线连续,可以提前用df.fillna(method='ffill')或者df.fillna(0)来处理缺失值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:19:04