如何使用熊猫计算每个类别的总数和百分比

时间:2018-07-18 20:12:41

标签: python python-2.7 pandas

我有一个数据集,其中的一列称为Ratings从1到5。结果应该如下:

Rating  Count  Count %
1         10    6.66%
2         20    13.33%
3         30    20.00%
4         40    26.66%
5         50    33.33%

总评分:150

(1)所有百分比应近似于小数点后2位 (2)结果应位于列名称为“评分,计数和计数%”的数据框中

如何使用熊猫获得此结果?

1 个答案:

答案 0 :(得分:0)

使用数学和 apply 和字符串格式:

df.Count.div(df.Count.sum()).apply('{0:.2%}'.format)

0     6.67%
1    13.33%
2    20.00%
3    26.67%
4    33.33%
Name: Count, dtype: object
相关问题