Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculating percent of 'group' total without creating new pandas dataframe

I’m trying to add a new series to a dataframe that calculates the percent of group total. Thing is, I don’t want a new dataframe. Here is my sample data:

df:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

my desired output would be:

enter image description here

Any ideas, thanks in advance!

>Solution :

Following BigBen’s suggestion, you can calculate this as:

df['Percent total of male'] = df.groupby('Gender')['Amount'].transform(lambda x: x/x.sum())

Otherwise, in a more step-by-step approach you can also try:

df['Percent total of male'] = np.where(df['Gender'] == 'Male',df['Amount'] / df[df['Gender'] =='Male']['Amount'].sum(),df['Amount'] / df[df['Gender']!='Male']['Amount'].sum()

In which df['Amount'].sum() will be a scalar, and the division will calculate each rows value as % of total.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading