将数据框分成组,然后按组计算Cumprod

时间:2018-10-30 11:53:00

标签: python pandas numpy

我想将数据框分成n组,每组大小均匀:

group_size = math.ceil(len(df)/n)

然后我要计算每个组的cumprod。

例如:

 Val - Group - Cumprod
  1  -   0   -    1
  3  -   0   -    3
  5  -   0   -    15
  2  -   1   -    2
  3  -   1   -    6
  ..     ..       ..

感谢任何可能采取的方法的帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

使用Numpy定义分组数组

#            Number of Groups you want
#                         
a = np.arange(len(df)) * 2 // len(df)

df.assign(Cumprod=df.groupby(a).Val.cumprod())

   Val  Group  Cumprod
0    1      0        1
1    3      0        3
2    5      0       15
3    2      1        2
4    3      1        6

答案 1 :(得分:1)

使用qcutcumprod

n = 2
df['cut'] = pd.qcut(df.index,n,labels=range(n))
df['cumprod'] = df.groupby('cut')['values'].cumprod()