Categories
Python Answers

How to get percentage of total with groupby with Python Pandas?

Spread the love

Sometimes, we want to get percentage of total with groupby with Python Pandas.

In this article, we’ll look at how to get percentage of total with groupby with Python Pandas.

How to get percentage of total with groupby with Python Pandas?

To get percentage of total with groupby with Python Pandas, we can use the transform method.

For instance, we write

df['sales'] / df.groupby('state')['sales'].transform('sum')

to get the total with

df.groupby('state')['sales'].transform('sum')

Then we use that as the divisor for df['sales'] to divide each value in the sales column by the total.

Conclusion

To get percentage of total with groupby with Python Pandas, we can use the transform method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *