Enr*_*ini 5 python pandas rolling-computation
我想获取 Pandas Series 的每个滚动窗口中元素的索引。
对我有用的解决方案来自对现有问题的回答:我从答案中描述的函数中获得了window.index每个值。我只对上述功能感兴趣。windowrollingstep=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)
Run Code Online (Sandbox Code Playgroud)
但它的结果是TypeError: must be real number, not RangeIndex. 显然,该Rolling.apply方法仅接受基于每个窗口返回数字的函数。这些函数不能返回其他类型的对象。
Rolling我可以使用Pandas 类的其他方法吗?甚至是私有方法。
或者还有其他 Pandas 特定的功能来获取重叠滚动窗口的索引吗?
作为输出,我期望某种列表对象。每个内部列表应该计算每个窗口的索引值。原始s系列有[0, 1, 2, 3, 4, 5, 6]索引。因此,使用 a 滚动window=3,我期望结果如下:
[
[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
]
Run Code Online (Sandbox Code Playgroud)
apply之后的函数必须rolling为每个窗口返回一个数值。一种可能的解决方法是使用列表理解来迭代每个窗口并根据需要应用自定义转换:
[[*l.index] for l in s.rolling(3) if len(l) == 3]
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用sliding_window_view来完成相同的任务:
np.lib.stride_tricks.sliding_window_view(s.index, 3)
Run Code Online (Sandbox Code Playgroud)
或者甚至列表理解也可以很好地完成这项工作:
w = 3
[[*s.index[i : i + w]] for i in range(len(s) - w + 1)]
Run Code Online (Sandbox Code Playgroud)
结果
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
Run Code Online (Sandbox Code Playgroud)