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

Pandas重采样报错:'DataFrame'对象无'Day'属性,如何解决?

解决Pandas重采样时的AttributeError: 'DataFrame' object has no attribute 'Day'问题

嘿,这个问题我熟!咱们来一步步捋清楚:

你报错的核心原因很简单——你已经把Day列设置成DataFrame的索引了(代码里的.set_index('Day')干的这事),所以现在costs这个DataFrame里根本没有叫Day的列了,自然会触发AttributeError。

接下来给你两种靠谱的解决办法,按需选就行:

办法一:直接基于索引重采样(推荐)

既然Day已经是索引,而且它是日期格式,那直接对整个DataFrame(或者你需要的特定列)调用resample()就好,Pandas会自动用索引作为时间维度:

import pandas as pd
# 读取数据并设置Day为索引
costs = pd.read_csv(r'/Users/erikvanderveen/Downloads/resampling.csv', skiprows=2, thousands=',').set_index('Day')
# 重要!确保索引是datetime类型(从CSV读进来的日期可能是字符串,必须转一下)
costs.index = pd.to_datetime(costs.index)
pd.set_option('display.width', 1000)
print(costs.head(5))

# 对整个DataFrame按月重采样求均值
monthly_resampled_data = costs.resample('M').mean()

# 如果只需要对某一列(比如叫'Cost'的列)重采样,就这么写:
# monthly_resampled_data = costs['Cost'].resample('M').mean()

办法二:保留Day列同时设为索引(不推荐,除非你确实需要)

如果你之后还得把Day当普通列用,可以在设置索引的时候加个drop=False参数,让它既是索引又是列:

costs = pd.read_csv(r'/Users/erikvanderveen/Downloads/resampling.csv', skiprows=2, thousands=',').set_index('Day', drop=False)
costs.index = pd.to_datetime(costs.index)

# 这时候就能用costs.Day.resample('M').mean()了
monthly_resampled_data = costs.Day.resample('M').mean()

不过说实话,这种情况没必要,因为索引已经是日期了,直接用办法一更简洁高效。

最后提醒一句:一定要把索引转成datetime类型!不然Pandas识别不了日期,重采样还是会出问题哦~

内容的提问来源于stack exchange,提问作者Erik van der Veen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 00:27:33