Pandas滚动转置?

3
在pandas中,是否有可能将移动窗口转置为行?

pandas.DataFrame.rolling

>> df
    Close
0   3.69 
1   9.14 
2   9.49 
3   15.84
4   17.00
5   26.31

在pandas中有一个tolling操作,可以给我最后N个值的转置,但是我该如何将它们插入到行中呢?

>> df
    Close    1       2      3 
0   3.69     NaN     NaN    NaN
1   9.14     3.69    NaN    NaN
2   9.49     9.14    3.69   NaN
3   15.84    9.49    9.14   3.69
4   17.00    15.84   9.49   9.14
5   26.31    17.00   15.84  9.49
2个回答

6
我认为你需要使用 shift 函数:
N = 3
for x in range(1, N + 1):
    df[x] = df['Close'].shift(x)
print (df)
   Close      1      2     3
0   3.69    NaN    NaN   NaN
1   9.14   3.69    NaN   NaN
2   9.49   9.14   3.69   NaN
3  15.84   9.49   9.14  3.69
4  17.00  15.84   9.49  9.14
5  26.31  17.00  15.84  9.49

因为rolling使用了一些聚合函数,例如sum

N = 3
for x in range(1, N + 1):
    df[x] = df['Close'].rolling(x+1).sum()
print (df)
   Close      1      2      3
0   3.69    NaN    NaN    NaN
1   9.14  12.83    NaN    NaN
2   9.49  18.63  22.32    NaN
3  15.84  25.33  34.47  38.16
4  17.00  32.84  42.33  51.47
5  26.31  43.31  59.15  68.64

2
pandas需要一些思维转换才能高效使用 :) 谢谢! - Alex T
@AlexT - 很高兴能帮忙! - jezrael

0
pd.concat([df1.shift(i) for i in range(4)],axis=1)

   Close  Close  Close  Close
0   3.69    NaN    NaN    NaN
1   9.14   3.69    NaN    NaN
2   9.49   9.14   3.69    NaN
3  15.84   9.49   9.14   3.69
4  17.00  15.84   9.49   9.14
5  26.31  17.00  15.84   9.49

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接