get_dummies 和一起计数

2022-01-22 00:00:00 python-3.x pandas dataframe pivot

问题描述

我有一个数据框,其中包含不同的案例"作为行,其中有一个 id 和一个类别:

I have a dataframe with different "cases" as rows, in which there's an id and a category:

df = DataFrame({ 'id':[1122,3344,5566,5566,3344,5566,1122,3344], 
            'category':['health','transport','energy','energy','transport','transport','transport','energy']})

    category    id
0   health      1122
1   transport   3344
2   energy      5566
3   energy      5566
4   transport   3344
5   transport   5566
6   transport   1122
7   energy      3344

我正在尝试找到一种既可以获取类别的虚拟变量并对其进行计数的好方法,所以通过上面的示例我会得到:

I'm trying to find a good way to both get dummies of the categories and also count them, so with the above example I would get this:

     health  transport  energy
1122    1        1          0
3344    0        2          1
5566    0        1          2

有什么想法吗?


解决方案

你可以使用pivot_table() 方法:

In [71]: df.pivot_table(index='id', columns='category', aggfunc='size', fill_value=0)
Out[71]:
category  energy  health  transport
id
1122           0       1          1
3344           1       0          2
5566           2       0          1

或:

In [76]: df.pivot_table(index='id', columns='category', aggfunc='size', fill_value=0).rename_axis(None, 1)
Out[76]:
      energy  health  transport
id
1122       0       1          1
3344       1       0          2
5566       2       0          1

相关文章