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.