我有以下数据帧:
+------------+------------------+
| item | categories |
+------------+------------------+
| blue_shirt | ['red', 'white'] |
+------------+------------------+
| red_skirt | ['blue', 'red'] |
+------------+------------------+
我想换成这个:
+------------+-----+-------+------+
| item | red | white | blue |
+------------+-----+-------+------+
| blue_shirt | 1 | 1 | 0 |
+------------+-----+-------+------+
| red_skirt | 1 | 0 | 1 |
+------------+-----+-------+------+
以下是我尝试过的:
orders = orders.join(pd.get_dummies(orders['Categories'].explode()))
它创建了正确的列,但也创建了(很多)额外的行。我希望每个项目的末尾都有一行,就像上面的例子一样
您可以分解数据帧中的类别和轴:
印刷品:
我能够通过以下方法获得您想要的结果
步骤1:创建将在结果数据集中使用的列列表
可选:您可以通过将列转换为列表类型来确保
explode()
有效:taken from here步骤2:将代码与
pd.get_dummies()
一起使用,并创建1/0数据集。为了避免获得更多的行,我使用groupby.index
添加了一个额外的步骤:第3步:,I
concat
您的“项目”列具有上述结果,并使用在第一步中创建的列列表获得所需的结果:一个块中的所有代码:
相关问题 更多 >
编程相关推荐