【发布时间】:2021-12-31 23:06:51
【问题描述】:
假设我们有这个df:
df = pd.DataFrame({
'string': ['blue',
'blue,red',
'red',
'purple',
'blue,red,green,yellow,magenta,purple',
'',
'yellow,purple']})
假设我们想在每个逗号处拆分这些字符串并将它们放入新列中。如发现这里 (How can I separate text into multiple values in a CSV file using Python?) 和这里 (Split one column into multiple columns by multiple delimiters in Pandas),我们可以使用 str.split 所以:
df[['blue', 'red', 'green', 'yellow', 'magenta', 'purple']] = df['string'].str.split(',',expand=True)
df
结果:
string blue red green yellow magenta purple
0 blue blue None None None None None
1 blue,red blue red None None None None
2 red red None None None None None
3 purple purple None None None None None
4 blue,red,green,yellow,magenta,purple blue red green yellow magenta purple
5 None None None None None
6 yellow,purple yellow purple None None None None
索引 0、1 和 4 按我的意愿工作,颜色在新列中正确分类。
对于其他索引,颜色分类错误。请注意,上面链接的示例不能解决我的问题,因为它们没有丢失数据点/级别。我该如何解决? (另外,为索引 5 的“蓝色”列添加“无”?)
非常感谢
【问题讨论】:
标签: python pandas string dataframe