Cumulative sum of a column in pandas python

Cumulative sum of a column in pandas python is carried out using cumsum() function. Let’s see how to

  • Get the cumulative sum of a column in pandas dataframe in python With an example

First let’s create a dataframe


import pandas as pd
import numpy as np

#Create a DataFrame
df1 = {
     'Name':['George','Andrea','micheal','maggie','Ravi','Xien','Jalpa'],
   'Mathematics_score':[62,47,55,74,32,77,86]}

df1 = pd.DataFrame(df1,columns=['Name','Mathematics_score'])
print(df1)

df1 will be

Cumulative sum of a column in pandas python 1

 

 Cumulative sum of a column in a pandas dataframe python 

Cumulative sum of a column in pandas is computed using cumsum() function and stored in the new column namely cumulative_sum as shown below


df1['cumulative_sum'] = df1.Mathematics_score.cumsum()
print(df1)

so resultant dataframe will be

Cumulative sum of a column in pandas python 2

Cumulative sum of a column in pandas python                                                                                                                Cumulative sum of a column in pandas python