get_dummies 并一起数数

cas*_*tor 3 pivot dataframe python-3.x pandas

我有一个具有不同“案例”作为行的数据框,其中有一个 id 和一个类别:

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
Run Code Online (Sandbox Code Playgroud)

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

     health  transport  energy
1122    1        1          0
3344    0        2          1
5566    0        1          2
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Max*_*axU 6

您可以使用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
Run Code Online (Sandbox Code Playgroud)

或者:

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
Run Code Online (Sandbox Code Playgroud)