我想从分类数据创建一键编码数据,你可以在这里看到这些数据。
Label1 Label2 Label3 0 Street fashion Clothing Fashion1 Clothing Outerwear Jeans2 Architecture Property Clothing3 Clothing Black Footwear4 White Photograph Beauty
对我来说的问题是,一个特定的标签(例如服装)可以出现在label1、label2或label3中。我尝试使用pd.get_dummies
,但这创建了如下数据:
Label1_Clothing Label2_Clothing Label3_Clothing 0 0 1 01 1 0 02 0 0 1
有没有办法为每个标签只拥有一个虚拟变量列?这样更像是:
Label_Clothing Label_Street Fashion Label_Architecture 0 1 1 01 1 0 02 1 0 1
我对编程相当新手,将非常感谢您的帮助。
最好的祝愿,Bernardo
回答:
您可以将数据框堆叠成一个单一的Series
,然后从中获取虚拟变量。从那里,您可以取外层级的最大值,以将数据折叠回其原始形状,同时保持标签的位置:
dummies = pd.get_dummies(df.stack()).max(level=0)print(dummies) Architecture Beauty Black Clothing Fashion Footwear Jeans Outerwear Photograph Property Street fashion White0 0 0 0 1 1 0 0 0 0 0 1 01 0 0 0 1 0 0 1 1 0 0 0 02 1 0 0 1 0 0 0 0 0 1 0 03 0 0 1 1 0 1 0 0 0 0 0 04 0 1 0 0 0 0 0 0 1 0 0 1