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

提取日期年份并绘制产品年度柱状图:修复DataFrame属性错误

解决DataFrame无Date属性问题并生成年度产品柱状图

咱们先理清楚报错的原因:你已经把Date列设置成DataFrame的索引了,这时候Date不再是普通数据列,自然没法通过df.Date去访问它,所以才会弹出'DataFrame' object has no attribute 'Date'的错误提示。

下面给你两种正确生成Year列的方法,以及后续绘制柱状图的完整步骤:

方法一:保留Date为普通列(不设为索引)

这种方式更直观,适合后续还需要用原始日期做其他分析的场景:

import pandas as pd
import matplotlib.pyplot as plt

# 读取数据,解析日期,不将Date设为索引
df = pd.read_csv('products.csv', sep=';', usecols=['Date','product1','product2','product3'], parse_dates=['Date'])

# 生成Year列:两种格式可选
# 方式1:得到字符串类型的年份(如'2018')
df['Year'] = df['Date'].dt.strftime('%Y')
# 方式2:得到整数类型的年份(如2018),后续分组计算更便捷
# df['Year'] = df['Date'].dt.year

方法二:已将Date设为索引,通过索引提取年份

如果你已经完成了索引设置,直接通过DataFrame的索引来提取年份即可:

import pandas as pd
import matplotlib.pyplot as plt

# 读取数据并设置Date为索引
df = pd.read_csv('products.csv', sep=';', usecols=['Date','product1','product2','product3'], parse_dates=['Date'])
df.set_index('Date', inplace=True)

# 通过索引生成Year列
# 方式1:字符串年份
df['Year'] = df.index.dt.strftime('%Y')
# 方式2:整数年份
# df['Year'] = df.index.dt.year

按年份绘制柱状图

生成Year列后,需要先按年份聚合数据(比如求和年度总数量),再绘制柱状图:

# 按年份分组,计算各产品的年度总量(如果需要均值就替换成.mean())
yearly_summary = df.groupby('Year')[['product1','product2','product3']].sum()

# 绘制柱状图
yearly_summary.plot(kind='bar', figsize=(10, 6), rot=0)
plt.title('各产品年度数量统计')
plt.xlabel('年份')
plt.ylabel('总数量')
plt.legend(title='产品类型')
plt.tight_layout()  # 自动调整布局,避免标签被截断
plt.show()

这样就能得到清晰的按年份分组的产品数量柱状图啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 17:37:43