我有以下数据框:
+------------+------------------+
| 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()))
它创建了正确的列,但它也创建了(很多)额外的行。我希望每个项目最后一行,如上例所示。
最佳答案
你也可以使用 pandas 的 .str 方法用一行代码解决这个问题
df['categories'].str.join('|').str.get_dummies()
“类别” 列的每个单元格内的格式必须是一个列表。如果它是其他字符串,您可以使用 .apply 函数将其设为列表。例如,如果 'categories' 列的内容是一个保存为字符串的列表:
df['categories'].apply(lambda x: eval(x)).str.join('|').str.get_dummies()
关于python - Pandas |在列中列出到二进制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66940757/