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

I tried with

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

除了非常缓慢,同时也忽略了"a,b"并分裂。

使用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

最新更新