Cumsum 作为现有 Pandas 数据中的新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41859311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cumsum as a new column in an existing Pandas data
提问by user1124702
I have a pandas dataframe defined as:
我有一个Pandas数据框定义为:
A B SUM_C
1 1 10
1 2 20
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:
我想做 SUM_C 的累积总和,并将其作为新列添加到同一数据帧中。换句话说,我的最终目标是拥有一个如下所示的数据框:
A B SUM_C CUMSUM_C
1 1 10 10
1 2 20 30
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.
在 group() 上的 Pandas 中使用 cumsum显示了生成新数据框的可能性,其中列名 SUM_C 被替换为累积总和。但是,我的要求是将累积总和作为新列添加到现有数据框中。
Thank you
谢谢
回答by blacksite
Just apply cumsum
on the pandas.Series
df['SUM_C']
and assign it to a new column:
刚申请cumsum
的pandas.Series
df['SUM_C']
,并将其分配给一个新的列:
df['CUMSUM_C'] = df['SUM_C'].cumsum()
Result:
结果:
df
Out[34]:
A B SUM_C CUMSUM_C
0 1 1 10 10
1 1 2 20 30