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:
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:
- Cumulative product of column in pandas python
- Cumulative sum of a column in pandas python
- Difference of two columns in pandas dataframe – python
- Sum of two or more columns of pandas dataframe in python
- Sort column in pandas dataframe python
- Groupby sum in pandas dataframe python
- Groupby count in pandas dataframe python
- Groupby mean in pandas dataframe python
further details about cumsum() function is in documentation.