Cumulative percentage of a column in pandas python

Cumulative percentage of a column in pandas python is carried out using sum() and cumsum() function in roundabout way. cumulative percentage of the column is calculated in the roundabout way in two methods as shown below. Let’s see how to

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

 

Desired result : Cumulative percentage of column:

cumulative percentage of the dataframe in pandas python 0a

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 percentage of a column in a pandas dataframe python : Method 1

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

##### cumulative percentage of column
df1['cumulative_percentage'] = 100*df1.Mathematics_score.cumsum()/df1.Mathematics_score.sum()
df1

so resultant dataframe will be

 

 

Cumulative percentage of a column in a pandas  : Method 2

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

##### cumulative percentage of column : Method 2
df1['cumulative_percentage'] = (df1.Mathematics_score.cumsum() / df1.Mathematics_score.sum()) * 100
df1

so resultant dataframe will be,


Other Related Topics:

further details about cumsum() function is in documentation.

Cumulative percentage of a column in pandas python prev                                                                                                           Cumulative percentage of a column in pandas python

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.