Pandas重采样报错:索引为DateTimeIndex仍提示仅支持时间索引
时间序列重采样报错解决记录
问题现象
处理小时级时间序列数据时,尝试通过重采样计算不同时间粒度的均值,持续触发错误:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'
数据概览
数据框头部内容如下:
DateTimeUtc DK1 ... SE3 SE4 DateTimeUtc ... 2022-01-01 00:00:00 2022-01-01 00:00:00 1691.712 ... -112.99925 93.56625 2022-01-01 01:00:00 2022-01-01 01:00:00 1244.341 ... 68.27500 345.15800 2022-01-01 02:00:00 2022-01-01 02:00:00 927.078 ... 308.46300 648.40400 2022-01-01 03:00:00 2022-01-01 03:00:00 612.140 ...
尝试过程及问题
初始代码中,已将DateTimeUtc列转为Datetime类型并设置为索引,同时保留了该列的副本:
import pandas as pd path = r'C:\Users\ERROR_2022.csv' df = pd.read_csv(path) df.columns = df.columns.str.replace('Unnamed: 0', 'DateTimeUtc') # 必要格式调整 df = df.set_index(pd.DatetimeIndex(df['DateTimeUtc']))
之后尝试指定on参数重采样:
weekly_summary = df.resample('W', on='DateTimeUtc')['DK1'].sum()
但原错误依旧。删除DateTimeUtc列后再次运行该代码,又触发新错误:
KeyError: 'The grouper name DateTimeUtc is not found'
最终解决方案
删除冗余的DateTimeUtc列,直接基于已设置的Datetime索引进行重采样:
df.drop('DateTimeUtc', axis = 1, inplace = True) # 重采样计算日均值 daily_summary = df.resample('D')['DK1'].mean()
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

