Python 对出现在多列中的单词进行一次热编码
我想从分类数据中创建热编码数据,您可以在这里看到Python 对出现在多列中的单词进行一次热编码,python,pandas,machine-learning,one-hot-encoding,dummy-variable,Python,Pandas,Machine Learning,One Hot Encoding,Dummy Variable,我想从分类数据中创建热编码数据,您可以在这里看到 Label1 Label2 Label3 0 Street fashion Clothing Fashion 1 Clothing Outerwear Jeans 2 Architecture Property Clothing 3 Clothing Bl
Label1 Label2 Label3
0 Street fashion Clothing Fashion
1 Clothing Outerwear Jeans
2 Architecture Property Clothing
3 Clothing Black Footwear
4 White Photograph Beauty
问题是(对我来说)一个特定的标签(例如衣服)可以在标签1、标签2或标签3中。我尝试了pd.get_dummies
,但这产生了如下数据:
Label1_Clothing Label2_Clothing Label3_Clothing
0 0 1 0
1 1 0 0
2 0 0 1
有没有办法让每个标签只包含一个虚拟变量列?相反地:
Label_Clothing Label_Street Fashion Label_Architecture
0 1 1 0
1 1 0 0
2 1 0 1
我对编程非常陌生,非常感谢您的帮助
最好的,
Bernardo您可以将数据帧堆叠到单个
系列中
,然后从中获取假人。从这里开始,在保持标签位置的同时,使用外部标高的最大值将数据折叠回其原始形状:
dummies = pd.get_dummies(df.stack()).max(level=0)
print(dummies)
Architecture Beauty Black Clothing Fashion Footwear Jeans Outerwear Photograph Property Street fashion White
0 0 0 0 1 1 0 0 0 0 0 1 0
1 0 0 0 1 0 0 1 1 0 0 0 0
2 1 0 0 1 0 0 0 0 0 1 0 0
3 0 0 1 1 0 1 0 0 0 0 0 0
4 0 1 0 0 0 0 0 0 1 0 0 1
非常感谢你!我希望你有一个非常愉快的一天/晚上:)