TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex when dtype is datetime64[ns]

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex when dtype is datetime64[ns]

我在 Python 中有一个 pandas 数据框,其列如下:

 df.Timestamp
...   ..................
129   2018-09-12 21:40:00
130   2018-09-12 21:50:00
131   2018-09-12 22:00:00
132   2018-09-12 22:10:00
133   2018-09-12 22:20:00
134   2018-09-12 22:30:00
135   2018-09-12 22:40:00
136   2018-09-12 22:50:00
137   2018-09-12 23:00:00
138   2018-09-12 23:10:00
139   2018-09-12 23:20:00
140   2018-09-12 23:30:00
141   2018-09-12 23:40:00
142   2018-09-12 23:50:00
Name: Timestamp, dtype: datetime64[ns]

单个元素的类型是:

type(df.Timestamp[0])
datetime.datetime

当我尝试重新采样时,出现以下错误:

df.Timestamp.resample('2H')

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex

我已经试过了pd_todatetime,但还是不行。 据我所知,我的数据类型是正确的 datetime.datetime None 我查看的解决方案中有针对此类问题的答案。

有什么解决办法?

有 2 种可能的解决方案 - resample or create DatetimeIndex by set_index 中的参数 on

最后添加一些聚合函数,如 summean...:[=​​19=]

df.resample('2H', on='Timestamp').sum()

df.set_index('Timestamp').resample('2H').sum()