【问题标题】:TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex when dtype is datetime64[ns]TypeError:仅当 dtype 为 datetime64[ns] 时对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效
【发布时间】:2019-03-17 08:05:06
【问题描述】:

我在 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:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效

我尝试过pd_todatetime,但它不起作用。 据我所知,我的数据类型是正确的,因为它是 datetime.datetime 我查看的所有解决方案都没有解决此类问题。

有什么解决办法?

【问题讨论】:

  • 这意味着您需要将Timestamp 列设置为索引

标签: python pandas datetime dataframe sampling


【解决方案1】:

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

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

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

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

【讨论】:

  • @Sandeep Kadapa - 谢谢。
猜你喜欢
  • 2020-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-08-23
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
  • 1970-01-01
  • 2015-08-31
相关资源
最近更新 更多