Pandas Group By And Get Dummies
Benzersiz değer başına kukla değişkenler elde etmek istiyorum. Fikir, veri çerçevesini çok etiketli bir hedefe dönüştürmektir. Nasıl yapabilirim?
Veri:
ID L2
A Firewall
A Security
B Communications
C Business
C Switches
Istenilen çıktı:
ID Firewall Security Communications Business Switches
A 1 1 0 0 0
B 0 0 1 0 0
C 0 0 0 1 1
Denedim pd.pivot_tableama toplanacak bir sütun gerektiriyor. Bu bağlantıya da cevap vermeyi denedim, ancak yalnızca ikili kukla sütunlara dönüştürmek yerine değerleri toplar. Yardımın için çok minnettar olurum. Çok teşekkürler!
Yanıtlar
Edelim set_indexo zaman get_dummiesher kimliği birden yinelenen sahip olmalarından dolayı, gerek, sumbirliktelevel = 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, sonra boolean'a dönüştür:
pd.crosstab(df['ID'],df['L2']).astype(bool)
Çıktı:
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
pivot_tabledeğiştirirseniz kullanabilirsiniz 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
ve belki reset_indexsonunda kimliği sütun olarak koymak
Bunu deneyebilirsiniz:
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)
Çıktı:
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
Alternatif seçenek:
df = df.groupby(['ID'])['L2'].apply(','.join).str.get_dummies(",").reset_index()
print(df)