【发布时间】:2022-01-11 16:21:48
【问题描述】:
我想获取 Pandas 系列的每个滚动窗口中元素的索引。
对我有用的解决方案是this 对现有问题的回答:对于从答案中描述的rolling 函数获得的每个window,我得到window.index。对于上述功能,我只对step=1 感兴趣。
但是这个函数并不特定于 DataFrames 和 Series,它适用于基本的 Python 列表。 是不是有一些利用 Pandas 滚动操作的功能?
我试过Rolling.apply方法:
s = pd.Series([1, 2, 3, 4, 5, 6, 7])
rolling = s.rolling(window=3)
indexes = rolling.apply(lambda x: x.index)
但它会导致TypeError: must be real number, not RangeIndex。显然,Rolling.apply 方法只接受基于每个窗口返回一个数字的函数。函数不能返回其他类型的对象。
我可以使用 Pandas Rolling 类的其他方法吗?甚至是私有方法。
或者是否有任何其他 Pandas 特定的功能来获取重叠滚动窗口的索引?
预期输出
作为输出,我期望某种列表对象。每个内部列表都应该计算每个窗口的索引值。
原来的s 系列有[0, 1, 2, 3, 4, 5, 6] 作为索引。
因此,使用window=3 滚动,我希望结果类似于:
[
[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
]
【问题讨论】:
标签: python pandas rolling-computation