You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按逗号分割字符串,排除逗号后紧跟空格的情况

解决方案

你需要使用正则表达式作为分割规则,指定仅在逗号后紧跟非空白字符的位置进行分割,具体实现如下:

  1. 先清理字符串首尾的方括号(如果你的DataFrame元素包含[])
  2. 使用正则分割符,(?=\S)进行拆分,其中:
    • , 匹配目标逗号
    • (?=\S) 是正向预查断言,确保逗号后面紧跟的是非空白字符(即没有空格),这样就会跳过那些逗号后带空格的位置

示例代码:

# 清理首尾方括号
df_clean = df[0].str.strip('[]')
# 按指定规则分割并展开为DataFrame
df1 = df_clean.str.split(',(?=\\S)', expand=True)

测试你的示例数据,分割后会得到以下规整的结果:

0123
target:2targettwo:3name:stars, the suncolour=blue
target:2targettwo:3name:planet, marscolour=red
target:2targettwo:4name:neptunecolour=blue

这样就能保证列数一致,不会误分割带空格的逗号位置。

内容的提问来源于stack exchange,提问作者Rob_does_physics

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:55:05