Pandas Group By And Get Dummies

Aug 28 2020

一意の値ごとにダミー変数を取得させたい。アイデアは、データフレームをマルチラベルターゲットに変えることです。どうすればいいですか?

データ:

           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ましたが、集計するには列が必要です。私もこのリンクで答えを試しましたが、バイナリのダミー列に変換するのではなく、値を合計します。よろしくお願いします。どうもありがとう!

回答

2 BENY Aug 28 2020 at 15:34

私たちをみましょう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
4 QuangHoang Aug 28 2020 at 15:42

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
1 Ben.T Aug 28 2020 at 15:42

pivot_table変更すると使用できますaggfunc=any

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を列として置くために

1 SoumendraMishra Aug 28 2020 at 15:48

あなたはこれを試すことができます:

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)