[英]Python pandas: Calculating percentage with groups using groupby
I have a data frame which contains the information of customer type.我有一个包含客户类型信息的数据框。 I used groupby
to count the type of customer within each category using following command:我使用groupby
使用以下命令计算每个类别中的客户类型:
df.groupby('Classification')['customer'].count()
It produces following result:它产生以下结果:
Classification
Agriculture 2366
Commercial 21904
Council 414
Industrial 911
Residential 51018
Name: ICP, dtype: int64
Now I want to calculate the percentage of each type of classification.现在我想计算每种分类的百分比。 I used follwoing command to calculate:我使用以下命令来计算:
df.groupby(level=0).apply(lambda x: 100 * x/float(x.sum()))
But it produces following output:但它产生以下输出:
Classification
Agriculture 100.0
Commercial 100.0
Council 100.0
Industrial 100.0
Residential 100.0
Name: ICP, dtype: float64
I want to show the percentage of each type of classification.我想显示每种分类的百分比。 Not sure where am I making the mistake.不知道我在哪里犯了错误。 Any help would be really appreciated.任何帮助将非常感激。
以下应该工作:
df.groupby('Classification')['customer'].count()/df['customer'].count()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.