[英]TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex when dtype is datetime64[ns]
I have a pandas dataframe in Python with a column such as this: 我在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 of individual element is: 单个元素的类型为:
type(df.Timestamp[0])
datetime.datetime
When I try resampling, following error occurs: 当我尝试重采样时,发生以下错误:
df.Timestamp.resample('2H')
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex TypeError:仅对DatetimeIndex,TimedeltaIndex或PeriodIndex有效
I have tried pd_todatetime
but it does not work. 我已经尝试过pd_todatetime
但是它不起作用。 As far as I know, my datatype is right as it is datetime.datetime None of the solutions I viewed had an answer for this type of problem. 据我所知,我的数据类型是正确的,因为它是datetime.datetime我看过的解决方案都没有针对此类问题的答案。
What can be the solution? 有什么解决方案?
There are 2 possible solutions - parameter on
in resample
or create DatetimeIndex
by set_index
. 有2种可能的解决方案-在resample
on
参数on
或通过set_index
创建DatetimeIndex
。
Last add some aggregate function like sum
, mean
...: 最后添加一些聚合函数,例如sum
, mean
...:
df.resample('2H', on='Timestamp').sum()
df.set_index('Timestamp').resample('2H').sum()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.