简体   繁体   English

在不创建新 pandas dataframe 的情况下计算“组”总数的百分比

[英]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.我正在尝试将一个新系列添加到计算组总数百分比的 dataframe 中。 Thing is, I don't want a new dataframe.问题是,我不想要一个新的 dataframe。 Here is my sample data:这是我的示例数据:

df:东风:

在此处输入图像描述

my desired output would be:我想要的 output 将是:

在此处输入图像描述

Any ideas, thanks in advance!任何想法,提前谢谢!

Following BigBen's suggestion, you can calculate this as:按照 BigBen 的建议,您可以将其计算为:

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.其中df['Amount'].sum()将是一个标量,除法将计算每行的值占总数的百分比。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM