【问题标题】:How to calculate count and percentage of total for each category using pandas如何使用熊猫计算每个类别的总数和百分比
【发布时间】:2018-12-26 20:40:31
【问题描述】:

我有一个数据集,其中有一列称为从 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) 结果应该在一个列名的数据框中——Rating, Count & Count%

如何使用 pandas 得到这个结果?

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    使用数学和 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
    

    【讨论】:

    • 它不起作用 - 'DataFrame' 对象没有属性 'Count' - 我们还需要将结果存储在单独的列中
    • 对解决方案有任何想法吗?
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 2015-10-07
    • 2022-11-19
    • 2021-10-09
    • 2015-01-09
    • 1970-01-01
    相关资源
    最近更新 更多