我想计算不相邻行的滚动乘积,如照片中所示的每五行值的乘积(结果是蓝色单元格中数据的乘积等等)。

我现在能做的最好的方法是:
temp = pd.DataFrame([range(20)]).transpose()
df = temp.copy()
df['shift1'] = temp.shift(5)
df['shift2'] = temp.shift(10)
df['shift3'] = temp.shift(15)
result = df.product(axis=1)但是,它看起来很麻烦,因为我想动态地更改行步骤。有人能告诉我是否有更好的方法来驾驭这个吗?谢谢
发布于 2022-10-28 07:26:23
您可以将groupby.cumprod/groupby.prod与模块5一起用作石斑鱼:
import numpy as np
m = np.arange(len(df)) % 5
# option 1
df['result'] = df.groupby(m)['data'].cumprod()
# option 2
df.loc[~m.duplicated(keep='last'), 'result2'] = df.groupby(m)['data'].cumprod()
# or
# df.loc[~m.duplicated(keep='last'),
# 'result2'] = df.groupby(m)['data'].prod().to_numpy()产出:
data result result2
0 0 0 NaN
1 1 1 NaN
2 2 2 NaN
3 3 3 NaN
4 4 4 NaN
5 5 0 NaN
6 6 6 NaN
7 7 14 NaN
8 8 24 NaN
9 9 36 NaN
10 10 0 NaN
11 11 66 NaN
12 12 168 NaN
13 13 312 NaN
14 14 504 NaN
15 15 0 0.0
16 16 1056 1056.0
17 17 2856 2856.0
18 18 5616 5616.0
19 19 9576 9576.0https://stackoverflow.com/questions/74231858
复制相似问题