【问题标题】:Pandas dataframe.resample TypeError 'Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'Pandas dataframe.resample TypeError '仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但获得了 'RangeIndex' 的实例
【发布时间】:2021-05-03 04:09:44
【问题描述】:

我有一个时间序列数据帧 df 我想重新采样,以便我可以将它与另一个具有不同采样频率的数据帧进行对比。时间以纪元时间开始,所以我将它们转换为日期时间:

>>> df
                 x         y
0     1.541376e+09  0.044084
1     1.541376e+09  0.044309
2     1.541376e+09  0.044772
3     1.541376e+09  0.044320
4     1.541376e+09  0.046859
...            ...       ...
4122  1.541462e+09  0.278618
4123  1.541462e+09  0.276922
4124  1.541462e+09  0.274893
4125  1.541462e+09  0.276190
4126  1.541462e+09  0.273271

[4127 rows x 2 columns]

df.x = df.x.apply(datetime.datetime.fromtimestamp)
>>> df
                           x         y
0    2018-11-05 13:00:21.884  0.044084
1    2018-11-05 13:00:44.581  0.044309
2    2018-11-05 13:01:07.276  0.044772
3    2018-11-05 13:01:29.973  0.044320
4    2018-11-05 13:01:52.670  0.046859
...                      ...       ...
4122 2018-11-06 12:58:11.260  0.278618
4123 2018-11-06 12:58:33.955  0.276922
4124 2018-11-06 12:58:56.652  0.274893
4125 2018-11-06 12:59:19.349  0.276190
4126 2018-11-06 12:59:42.046  0.273271

[4127 rows x 2 columns]

然后我尝试使用 df.resample,我得到 TypeError:仅对 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但得到了一个“RangeIndex”实例。

查看df.x[o]的类型,不是datetime.datetime而是pandas._libs.tslibs.timestamps.Timestamp,看起来是等价的吗? 无论如何,如果有人能告诉我如何让这个 resample() 工作,我将不胜感激。

【问题讨论】:

  • df.set_index('x', inplace=True)

标签: python python-3.x pandas dataframe datetime


【解决方案1】:

好的,看起来如果我按照 Ynjxsjmh 的建议设置索引(确保它实际上是就地完成的......),然后 resample() 工作。但是它返回了一些奇怪的对象,然后我必须对其执行 .sum() ,它会返回我想要的数据框。

令人讨厌的是,我的两个数据框的长度仍然相差 1 行,但我只是用 df.drop(df.tail(1).index, inplace = True) 删除了其中一个数据框的最后一行,它起作用了.

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2015-08-31
    • 1970-01-01
    • 2018-06-23
    相关资源
    最近更新 更多