通过定界符Pandas将列拆分为未知列数 [英] Split Column into Unknown Number of Columns by Delimiter Pandas
本文介绍了通过定界符Pandas将列拆分为未知列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据逗号/空格分隔将一列拆分为多列.
I am trying to split a column into multiple columns based off comma/space seperation.
我的数据框当前看起来像
my dataframe currently looks like
Item Colors
0 ID-1 Red, Blue, Green
1 ID-2 Red, Blue
2 ID-3 Blue, Green
3 ID-4 Blue
4 ID-5 Red
我想像这样将颜色"列转换为红色,蓝色和绿色:
I would like to transform the 'Colors' column into Red, Blue and Green like this:
Item Red Blue Green
0 ID-1 1 1 1
1 ID-2 1 1 0
2 ID-3 0 1 1
3 ID-4 0 1 0
4 ID-5 1 0 1
我真的不知道该怎么做. 任何帮助将不胜感激.
I really have no idea how to do this. Any help would be greatly appreciated.
推荐答案
您可以使用 get_dummies
You can using get_dummies
pd.concat([df,df.Colors.str.get_dummies(sep=', ')],1)
Out[450]:
Item Colors Blue Green Red
0 ID-1 Red,Blue,Green 1 1 1
1 ID-2 Red,Blue 1 0 1
2 ID-3 Blue,Green 1 1 0
3 ID-4 Blue 1 0 0
4 ID-5 Red 0 0 1
这篇关于通过定界符Pandas将列拆分为未知列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文