我有一个数据框,其中包含客户类型的信息。我使用groupby
使用以下命令来计算每个类别中的客户类型:
df.groupby('Classification')['customer'].count()
它产生以下结果:
Classification
Agriculture 2366
Commercial 21904
Council 414
Industrial 911
Residential 51018
Name: ICP, dtype: int64
现在,我想计算每种分类的百分比。我用follwoing命令来计算:
df.groupby(level=0).apply(lambda x: 100 * x/float(x.sum()))
但是会产生以下输出:
Classification
Agriculture 100.0
Commercial 100.0
Council 100.0
Industrial 100.0
Residential 100.0
Name: ICP, dtype: float64
我想显示每种分类的百分比。不知道我在哪里犯错。任何帮助将不胜感激。
答案 0 :(得分:2)
以下方法应该起作用:
df.groupby('Classification')['customer'].count()/df['customer'].count()