获取 Pandas Rolling window 的索引

Get indexes of Pandas Rolling window

我想获取 Pandas 系列的每个滚动 window 中元素的索引。

对我有用的解决方案来自 对现有问题的回答:我从 rolling 中描述的 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 方法只接受 return 一个基于每个 window 的数字的函数。这些函数不能 return 其他类型的对象。

我可以使用 Pandas Rolling class 的其他方法吗?甚至私有方法。

或者是否有任何其他 Pandas 特定的功能来获取重叠滚动的索引 windows?

预期输出

作为输出,我希望得到某种列表对象。每个内部列表应该计算每个 window 的索引值。 原来的 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],
]

rolling 之后的 apply 函数必须 return 每个 window 的数值。一种可能的解决方法是使用列表推导式遍历每个 window 并根据需要应用自定义转换:

[[*l.index] for l in s.rolling(3) if len(l) == 3]

或者您也可以使用 sliding_window_view 来完成同样的事情:

np.lib.stride_tricks.sliding_window_view(s.index, 3)

或者甚至列表理解也能很好地完成工作:

w = 3
[[*s.index[i : i + w]] for i in range(len(s) - w + 1)]

结果

[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]