如何在熊猫中设置数据透视表以计算总价值并得出百分比?

时间:2019-12-02 10:27:40

标签: pandas pivot-table

我是python和pandas的初学者。 我正在练习数据透视表。

这是我为练习而制作的数据。

enter image description here

1 个答案:

答案 0 :(得分:0)

假设源DataFrame如下:

    Id Status
0  747   good
1  587    bad
2  347   good
3  709   good

我认为 pivot 是一个错误的选择。 要计数个总值,更自然的解决方案是 value_counts 。 连同设置适当的列名,代码可以是:

res = df.Status.value_counts().reset_index()
res.columns = ['Status', 'total']

到目前为止,我们只有总数。要计算百分比,另一条指令 是必需的:

res['percentage'] = res.total / res.total.sum()

对于我的数据,结果是:

  Status  total  percentage
0   good      3        0.75
1    bad      1        0.25