多列中出现的单词的一键编码

我想从分类数据创建一键编码数据,你可以在这里看到这些数据。

        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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注