gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:10 24 4
gpt4 key购买 nike

我在 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我查看的所有解决方案都无法解决此类问题。

有什么解决办法?

最佳答案

有 2 种可能的解决方案 - resample 中的参数 on或通过 set_index 创建 DatetimeIndex .

最后添加一些聚合函数,如summean...:

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

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

关于python - TypeError : Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex when dtype is datetime64[ns],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52773627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com