汇总作为现有Pandas数据中的新列 [英] Cumsum as a new column in an existing Pandas data

查看:42
本文介绍了汇总作为现有Pandas数据中的新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义为的熊猫数据框:

I have a pandas dataframe defined as:

A   B   SUM_C      
1   1   10     
1   2   20   

我想做一个SUM_C的累加和,并将其作为新列添加到同一数据帧中.换句话说,我的最终目标是拥有一个如下所示的数据框:

I would like to do a cumulative sum of SUM_C and add it as a new column to the same dataframe. In other words, my end goal is to have a dataframe that looks like below:

A   B   SUM_C   CUMSUM_C       
1   1   10      10     
1   2   20      30   

在group()上的熊猫中使用cumsum 显示了生成的可能性一个新的数据框,其中列名SUM_C被替换为累积和.但是,我的要求是将累加总和作为新列添加到现有数据框中.

Using cumsum in pandas on group() shows the possibility of generating a new dataframe where column name SUM_C is replaced with cumulative sum. However, my ask is to add the cumulative sum as a new column to the existing dataframe.

谢谢

推荐答案

只需在pandas.Series df['SUM_C']上应用cumsum并将其分配给新列:

Just apply cumsum on the pandas.Series df['SUM_C'] and assign it to a new column:

df['CUMSUM_C'] = df['SUM_C'].cumsum()

结果:

df
Out[34]: 
   A  B  SUM_C  CUMSUM_C
0  1  1     10       10
1  1  2     20       30

这篇关于汇总作为现有Pandas数据中的新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆