Pandas 分组并获得假人

Pandas Group By And Get Dummies

我想为每个唯一值获取虚拟变量。想法是将数据框变成多标签目标。我该怎么做?

数据:

           ID                      L2
           A                 Firewall
           A                 Security
           B           Communications
           C                 Business
           C                 Switches

期望输出:

ID   Firewall  Security  Communications  Business   Switches
 A      1          1             0              0         0
 B      0          0             1              0         0
 C      0          0             0              1         1

我试过 pd.pivot_table 但它需要一个列来聚合。我也试过在 this link 上回答,但它对值求和而不是仅仅变成二进制虚拟列。非常感谢您的帮助。非常感谢!

让我们set_index然后get_dummies,因为每个ID都有多个重复项,我们需要sumlevel = 0

s = df.set_index('ID')['L2'].str.get_dummies().max(level=0).reset_index()
Out[175]: 
  ID  Business  Communications  Firewall  Security  Switches
0  A         0               0         1         1         0
1  B         0               1         0         0         0
2  C         1               0         0         0         1

crosstab,然后转换为布尔值:

pd.crosstab(df['ID'],df['L2']).astype(bool)

输出:

L2  Business  Communications  Firewall  Security  Switches
ID                                                        
A      False           False      True      True     False
B      False            True     False     False     False
C       True           False     False     False      True

如果您更改 aggfunc=any,则可以使用 pivot_table

print(df.pivot_table(index='ID', columns='L2', 
                     aggfunc=any, fill_value=False)\
        .astype(int))
L2  Business  Communications  Firewall  Security  Switches
ID                                                        
A          0               0         1         1         0
B          0               1         0         0         0
C          1               0         0         0         1

可能 reset_index 在末尾将 ID 作为列

你可以试试这个:

df1 = pd.read_csv("file.csv")
df2 = df1.groupby(['ID'])['L2'].apply(','.join).reset_index()
df3 = df2["L2"].str.get_dummies(",")
df = pd.concat([df2, df3], axis = 1)
print(df)

输出:

  ID                 L2  Business  Communications  Firewall  Security  Switches
0  A  Firewall,Security         0               0         1         1         0
1  B     Communications         0               1         0         0         0
2  C  Business,Switches         1               0         0         0         1

替代选项:

df = df.groupby(['ID'])['L2'].apply(','.join).str.get_dummies(",").reset_index()
print(df)