累积计数python向后

时间:2017-07-20 10:16:41

标签: python pandas

我有一个示例数据框如下

ID       count
1          10
2          20
3          40

因此,对于累积计数,我想实现

ID       count     cum Count
1          10         70
2          20         50 
3          40         40

知道怎么用熊猫做这个吗?

1 个答案:

答案 0 :(得分:2)

对交换顺序使用双[::-1]

df['cum Count'] = df['count'].iloc[::-1].cumsum().iloc[::-1]
print (df)
   ID  count  cum Count
0   1     10         70
1   2     20         60
2   3     40         40

Numpy解决方案:

df['cum Count'] = df['count'].values[::-1].cumsum()[::-1]
print (df)
   ID  count  cum Count
0   1     10         70
1   2     20         60
2   3     40         40