我需要在一个窗口上执行累积返回计算,其中函数在下一个窗口开始时重新启动。让我们看一个例子:
A = pd.DataFrame([100, 101, 102, 103, 104, 105, 106, 107, 108],
columns=['A'], index=[range(1,10)])
假设您将窗口大小定义为 3,鉴于我需要窗口的累积返回,所需的输出将为
A['B'] = function(A['A'], window=3)
A B
1 100 0
2 101 0.010000
3 102 0.020000
4 103 0
5 104 0.009709
6 105 0.019417
7 106 0
8 107 0.009434
9 108 0.018868
谢谢。
最佳答案
IIUC,您可以使用 groupby
来完成此操作:
>>> w = 3
>>> A["B"] = A.groupby(np.arange(len(A))//w)["A"].apply(lambda x: x/x.iloc[0]-1)
>>> A
A B
1 100 0.000000
2 101 0.010000
3 102 0.020000
4 103 0.000000
5 104 0.009709
6 105 0.019417
7 106 0.000000
8 107 0.009434
9 108 0.018868
关于python - 如何在 Pandas/Numpy 中同时实现具有非重叠和滚动特征的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25879735/