一个热与编码在python每行的多个分类值

问题描述 投票:1回答:1

我想实现一个热码的分类功能在Python 3.我注意到几个ID的已超过一个分类值。

我的表:

id  type
13   A
13   B
2    A
34   C
34   A
34   B

我的愿望输出:

id  type@A  type@B  type@C
13     1      1       0
2      1      0       0
34     1      1       1

我能做什么?

python one-hot-encoding
1个回答
3
投票

如果使用的是确定大熊猫,存储在数据框(名称df例如)和使用数据:

pd.crosstab(df['id'],df['type']).rename_axis(None,axis=1)

实施例下面:

import pandas as pd
d={'id': {0: 13, 1: 13, 2: 2, 3: 34, 4: 34, 5: 34},
'type': {0: 'A', 1: 'B', 2: 'A', 3: 'C', 4: 'A', 5: 'B'}}
df=pd.DataFrame(d)
print(df)

   id type
0  13    A
1  13    B
2   2    A
3  34    C
4  34    A
5  34    B

使用pd.crosstab()

df_new = pd.crosstab(df['id'],df['type']).rename_axis(None,axis=1).add_prefix('type@')
print(df_new)

     type@A  type@B  type@C
id                        
2        1       0       0
13       1       1       0
34       1       1       1
© www.soinside.com 2019 - 2024. All rights reserved.