33

I have a pandas dataframe defined as:

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:

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.

Thank you

Nihal
  • 5,106
  • 7
  • 23
  • 38
user1124702
  • 865
  • 4
  • 10
  • 22

2 Answers2

61

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

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
cs95
  • 330,695
  • 80
  • 606
  • 657
blacksite
  • 11,076
  • 8
  • 58
  • 102
  • Thank you. Correct answer for the question that was posed. I would like to also add that if we have more than two columns and would like to do the same, they process is below: Step:1: obviously work with a sorted data frame 2. Use df['CUM_D'] = df.groupby(['A','B'])['D'].cumsum(axis = 0). skipped 'C' in groupby as it is the column on which cumulative summation is being done. – user1124702 Jan 25 '17 at 19:53
  • This will fail if you have two columns with the same name. In that case, rename one of them before proceeding. – Josh Herzberg Jan 28 '20 at 18:52
0

Overview: you can use a dataframe aggregate and pass it an user defined function

def accumulate(values):
    """The accumulate function takes the offset previous numbers in a series and sums them.
      args: a dataframe with a 100 numbers
 """
    offset=0
    accumulate=[]
    for i in np.arange(len(values)):
        offset+=1
        accumulate.append(values[:offset].sum())
    
    return accumulate

  A=pd.DataFrame(np.arange(1,101), columns=['value'])

  A.aggregate(accumulate).plot()
Golden Lion
  • 2,792
  • 2
  • 19
  • 29