Python 用逗号和引号分解字符串
Python explode strings with comma and quotes
我有一个具有以下设置的数据集:
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"
并将它们拆分。
使用Series.str.strip
with Series.str.split
and last 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
我有一个具有以下设置的数据集:
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"
并将它们拆分。
使用Series.str.strip
with Series.str.split
and last 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