簡體   English   中英

Pandas dataframe.resample TypeError '僅對 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但獲得了“RangeIndex”實例

[英]Pandas dataframe.resample TypeError 'Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

我有一個時間序列 dataframe df 我想重新采樣,以便我可以 plot 它與另一個具有不同采樣頻率的 dataframe 對比。 時間從紀元時間開始,所以我將它們轉換為日期時間:

>>> 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() 工作,我將不勝感激。

好的,看起來如果我按照 Ynjxsjmh 的建議設置索引(確保它實際上是就地完成的......),然后 resample() 工作。 但它會返回一些奇怪的 object,然后我必須對其進行 do.sum(),它會返回我想要的 dataframe。

令人討厭的是,我的兩個數據幀的長度仍然相差 1 行,但我只是用 df.drop(df.tail(1).index, inplace = True) 刪除了其中一個數據幀的最后一行,它就起作用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM