How to calculate the Percentage of a column in Pandas ?
Last Updated :
29 Sep, 2023
A Percentage is calculated by the mathematical formula of dividing the value by the sum of all the values and then multiplying the sum by 100. This is also applicable in Pandas Dataframes.
Here, the pre-defined sum() method of pandas series is used to compute the sum of all the values of a column.
Syntax: Series.sum()
Return: Returns the sum of the values.
Formula:
df[percent] = (df['column_name'] / df['column_name'].sum()) * 100
Example 1: calculate the Percentage of a column in Pandas
Python3
import pandas as pd
import numpy as np
df1 = {
'Name' : [ 'abc' , 'bcd' , 'cde' ,
'def' , 'efg' , 'fgh' ,
'ghi' ],
'Math_score' : [ 52 , 87 , 49 ,
74 , 28 , 59 ,
48 ]}
df1 = pd.DataFrame(df1,
columns = [ 'Name' ,
'Math_score' ])
df1[ 'percent' ] = (df1[ 'Math_score' ] /
df1[ 'Math_score' ]. sum ()) * 100
df1
|
Output:
Example 2:
Python3
import pandas as pd
df1 = {
'Name' : [ 'abc' , 'bcd' , 'cde' ,
'def' , 'efg' , 'fgh' ,
'ghi' ],
'Math_score' : [ 52 , 87 , 49 ,
74 , 28 , 59 ,
48 ],
'Eng_score' : [ 34 , 67 , 25 ,
89 , 92 , 45 ,
86 ]
}
df1 = pd.DataFrame(df1,
columns = [ 'Name' ,
'Math_score' , 'Eng_score' ])
df1[ 'Eng_percent' ] = (df1[ 'Eng_score' ] /
df1[ 'Eng_score' ]. sum ()) * 100
df1
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...