All Courses

What is the method for calculating percentages with the Pandas groupby function?

By, a month ago
  • Bookmark

How can I calculate percentages using Pandas groupby?  

Calculating percentage
1 Answer

To calculate percentages with the Pandas groupby function, you can use the transform method in combination with the sum method.

Here's an example code snippet:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'Group': ['A', 'A', 'B', 'B', 'C', 'C'],
                   'Value': [10, 20, 30, 40, 50, 60]})

# group the dataframe by 'Group'
grouped = df.groupby('Group')

# calculate the sum for each group
group_sum = grouped['Value'].transform('sum')

# calculate the percentage for each row
percentage = df['Value'] / group_sum * 100

# add the percentage column to the dataframe
df['Percentage'] = percentage


In this example, we create a dataframe with two columns: 'Group' and 'Value'. We then group the dataframe by the 'Group' column using the groupby function. Next, we calculate the sum of 'Value' for each group using the transform method with the 'sum' function. We then calculate the percentage for each row by dividing the 'Value' column by the group sum and multiplying by 100. Finally, we add the percentage column to the original dataframe using df['Percentage'] = percentage. The resulting dataframe will have a new column called 'Percentage' with the percentage value for each row.

Your Answer


Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More