【问题标题】:pandas rolling how to retain the first time index of each time windowpandas rolling如何保留每个时间窗口的第一次索引
【发布时间】:2017-10-22 04:40:25
【问题描述】:

对我造成的所有困惑感到抱歉。 shift 方法工作得很好。事实证明,rolling 实际上保留了所有索引,我们所要做的就是向后移动,无论索引是否正常。


似乎 pandas rolling 方法总是保留每个时间窗口的 last 索引。例子:
import pandas as pd
import numpy as np

df = pd.DataFrame(data=np.random.randn(10, 2), columns=['a', 'b'], index=pd.date_range('20170101', periods=10))
rolling_spearmanr = df['a'].rank().rolling(window=3).corr(other=df['b'].rank())

print(rolling_spearmanr)

输出:

2017-01-01         NaN
2017-01-02         NaN
2017-01-03    0.654654
2017-01-04   -0.596040
2017-01-05    0.277350
2017-01-06    0.466321
2017-01-07    0.429838
2017-01-08   -0.921551
2017-01-09   -0.188982
2017-01-10   -0.277350
Freq: D, dtype: float64

不过,我想要的是一种让每个时间窗口保持其第一个索引的方法。可能吗?


请注意,简单地移动时间索引轴不会有帮助,因为时间窗口可能不是规则的(即使它们具有相同数量的索引)。例如,当时间索引是 business 天而不是连续的日历天时:
Index([2007-01-04, 2007-01-05, 2007-01-08, 2007-01-09, 2007-01-10, 2007-01-11], dtype='object', name='date')

现在如果我们用window=3 执行rolling,我想要的是类似

2017-01-04 ...
2017-01-09 ...

按照传统rolling method,会是

2017-01-08 ...
2017-01-11 ...

如您所见,如果您只是将输出日期向后移动2(因为每个时间窗口的长度为 3 个索引),您将不会获得所需的日期。

【问题讨论】:

  • @Bharathshetty 正如我所说,例如,如果索引是 [2007-01-04, 2007-01-05, 2007-01-08, 2007-01-09, 2007-01-10, 2007-01-11] 并且时间窗口是 3,那么我希望输出在删除 nan 后具有索引 ['2017-01-04', '2017-01-09']
  • 我认为滚动函数中根本没有考虑索引
  • @Bharathshetty 但rolling 确实保留了每个时间窗口中的最后一个索引。
  • 为什么不能反转数据框并使用相同的方法? df.iloc[::-1]
  • 您可以添加该代码吗?我是说你说的传统滚动方法

标签: python pandas date datetime


【解决方案1】:

想法 1
通过先反转数据帧然后再返回来破解...

(lambda d: d.a.rank().rolling(3).corr(d.b.rank()).iloc[::-1])(df.iloc[::-1])

2017-01-01    0.891042
2017-01-02    0.838628
2017-01-03    0.960769
2017-01-04   -0.897918
2017-01-05   -0.996616
2017-01-06    0.327327
2017-01-07    0.443533
2017-01-08   -0.178538
2017-01-09         NaN
2017-01-10         NaN
Freq: D, dtype: float64

想法2

使用pd.Series.shift

rolling_spearmanr.shift(-2)

2017-01-01    0.891042
2017-01-02    0.838628
2017-01-03    0.960769
2017-01-04   -0.897918
2017-01-05   -0.996616
2017-01-06    0.327327
2017-01-07    0.443533
2017-01-08   -0.178538
2017-01-09         NaN
2017-01-10         NaN
Freq: D, dtype: float64

【讨论】:

  • 我很难理解 Op 想要什么。非常不清楚
  • 使用pd.Series.rolling 时,聚合值会附加到窗口中的最后一个索引。 OP 正在询问如何将其附加到第一个索引。
  • @Bharathshetty 对我造成的混乱感到抱歉。我在想rolling 会“跳跃”而不是连续工作。结果证明这是一个愚蠢的错误。
  • @piRSquared 你认识我,wen 之前也用过这种方法,看输出索引我很困惑。我认为这是 Op 想要的输出。
猜你喜欢
  • 1970-01-01
  • 2012-08-12
  • 2020-09-30
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 1970-01-01
  • 2018-09-18
相关资源
最近更新 更多