Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对出现在多列中的单词进行一次热编码_Python_Pandas_Machine Learning_One Hot Encoding_Dummy Variable - Fatal编程技术网

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

非常感谢你!我希望你有一个非常愉快的一天/晚上:)