python - 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"
并拆分它们。
解决方案
Series.str.strip
与Series.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
推荐阅读
- javascript - 如何获取为当前js文件提供服务的url
- django - Django加入多个表
- json - 在 Pyspark 中使用唯一键解析 JSON
- javascript - 如何使用 jquery 将 angularjs 升级到 angular 9?
- react-native - 反应原生。节列表。如何限制项目并通过按钮单击全部显示?
- firebase - Xamarin.Forms 上的 Firebase 身份验证
- clickhouse - 在 Clickhouse 中控制字符串转义?
- python - BigQuery 架构更新而不丢失流缓冲区?
- process - Electron 是否有杀死无用渲染器进程的标准方法?
- .net-core - Razor Pages .Net Core:从 OnPost 打开一个新选项卡/窗口