首页 > 解决方案 > Python用逗号和引号分解字符串

问题描述

我有一个具有以下设置的数据集:

id   string_to_parse
1    "a","b"
2   "a,b","c"  
3   "c"

我需要把它放进去

id   string_to_parse
1    a
1    b
2    a,b
2    c
3    c

我试过了

exploded_ = df['string_to_parse'].map(lambda x:x\
    .replace('"','')\
    .split(",")).explode()

除了非常慢之外,它还会错过"a,b"并拆分它们。

标签: pythonpandasexplode

解决方案


Series.str.stripSeries.str.split和最后一起使用DataFrame.explode

df['string_to_parse'] = df['string_to_parse'].str.strip('"').str.split('","')
df  = df.explode('string_to_parse')
print (df)
   id string_to_parse
0   1               a
0   1               b
1   2             a,b
1   2               c
2   3               c

推荐阅读