我想让每个唯一的值得到虚拟变量。想法是把数据帧变成一个多标签的目标。我该怎么做呢?
数据:
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上尝试过答案,但它对值进行了求和,而不仅仅是将其转换为二进制虚拟列。我非常感谢你的帮助。非常感谢!
发布于 2020-08-28 15:34:18
让我们set_index然后get_dummies,因为我们有多个重复的每个ID,我们需要sum与level = 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发布于 2020-08-28 15:42:21
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发布于 2020-08-28 15:48:23
你可以试试这个:
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)https://stackoverflow.com/questions/63636807
复制相似问题