Groupby function for cumsum and reset it index
我的条件很简单:
如果当月总和 // 100:
print sum and reset cumsum index
其他:
keep cumsumming
这是我的数据:
1 2 3 4 5 | data = dict( Year=['2018', '2018', '2018', '2018', '2018', '2017', '2017', '2017'], Month=['08', '08', '04', '05', '05', '06', '02', '01'], Money=[26, 50, 25, 45, 20, 36, 84, 24] ) |
这是我的尝试:
1 2 3 4 5 6 7 8 9 10 | df = pd.DataFrame(data) df = df.groupby(['Year', 'Month']).sum() df['cum_y'] = df.groupby(['Year']).Money.cumsum() df['cum_m'] = df.groupby([lambda x: x // 100], level=0).Money.cumsum() df['cum_m'] = df.groupby(lambda x: [x if x // 100 else None]).Money.cumsum() df['cum_m'] = df.groupby(['Money']).agg(lambda x: x // 100).cumsum() |
我想要这样的东西:
1 2 3 4 5 6 7 8 | Money cum_y cum_m (Payout actually) Year Month 2017 01 24 24 x (means None) 02 84 108 108 - reset cumsum counter() 06 36 144 x (36) 2018 04 25 25 x (61) 05 65 90 126 - reset cumsum counter() 08 76 166 x (76) |
我知道应该尽可能避免迭代,但这里有一个使用迭代的解决方案:
1 2 3 4 5 6 7 8 9 10 11 | total = 0 Cumsum = [] for item in df.Money: total += item if total < 100: Cumsum.append(np.nan) else: Cumsum.append(total) total = 0 df['Cumsum'] = Cumsum |
输出:
1 2 3 4 5 6 7 8 | Money Cumsum Year Month 2017 01 24 NaN 02 84 108.0 06 36 NaN 2018 04 25 NaN 05 65 126.0 08 76 NaN |