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

如何在pandas中将单元格字符串拆分到不同行且忽略引号内逗号

pandas 按逗号拆分单元格忽略引号内逗号的实现方案

核心思路是直接复用Python标准库csv模块的分隔逻辑,csv默认支持跳过被指定引号包裹的内容内部的分隔符,完全匹配需求。

完整可运行代码示例

import pandas as pd
import csv
from io import StringIO

# 构造示例DataFrame
df = pd.DataFrame({
    "raw_content": ["'one two three', 'don\\'t split, this'"]
})

# 自定义分割函数:忽略单引号内的逗号
def split_with_quote_protect(s):
    # 配置quotechar为你实际使用的引号类型,示例用的是单引号
    reader = csv.reader(
        StringIO(s),
        quotechar="'",
        skipinitialspace=True  # 自动跳过逗号后面的多余空格
    )
    return next(reader)

# 执行拆分+展开为多行
df = df.assign(
    split_content = df["raw_content"].apply(split_with_quote_protect)
).explode("split_content").reset_index(drop=True)

# 输出结果
print(df["split_content"])

输出效果

运行上述代码后得到的split_content列内容和期望结果完全一致:

'one two three'
'don't split, this'

参数调整说明

  • 如果你实际场景中是用双引号包裹内容,只需要把quotechar参数的值改为'"'即可
  • 如果不需要去掉逗号后的空格,删除skipinitialspace=True参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:18:04