假设我有一个 pd.DataFrame 并想要计算滚动标准差。在 pandas 中,我可以使用
rolling(window=x).std()
,但它按列给我 SD。然而,我想要给定行中所有列的标准差。
以 pd 数据框为例
df = pd.DataFrame({'col1': [1,2,3,4,5,6], 'col2': [-1,-2,-3,-4,-5,-6], 'col3': [1,2,3,4,5,6]})
df
col1 col2 col3
0 1 -1 1
1 2 -2 2
2 3 -3 3
3 4 -4 4
4 5 -5 5
5 6 -6 6
例如,在计算窗口大小为 2 时,我希望第 2 行中的标准差为两行之和除以 6(或 6-1),这并不重要),因此: sum (2,-2,2,1,-1,1) / 6.
我尝试在融化的数据帧上计算它,但没有得到预期的结果:
df.reset_index().melt(id_vars='index').set_index('index')['value'].rolling(2).std()
有人知道该怎么做吗? 感谢您的反馈。
我认为最有效的是使用numpy:
from numpy.lib.stride_tricks import sliding_window_view as swv
N = 2
out = pd.Series(swv(df.to_numpy(), N, axis=0).std((1,2), ddof=1),
index=df.index[N-1:])