You need to enable JavaScript to run this app. 如何将数据库读取的DataFrame中字符串列按分隔符拆分为多列
优惠活动
大模型
产品
解决方案
定价
更多

如何将数据库读取的DataFrame中字符串列按分隔符拆分为多列

实现方案

使用Python的Pandas库可以快速完成该需求,操作逻辑如下:

  1. 先将values列的字符串按|和;两个分隔符一次性拆分,直接扩展为多列
  2. 对拆分后的列重命名,缺失位置默认填充NaN(对应SQL场景的NULL,也可显式替换为NULL字符串)
  3. 合并原表的id列得到最终结果

完整可运行代码

import pandas as pd

# 此处替换为你从数据库读取得到的原始DataFrame
df = pd.DataFrame({
    'id': [1, 2, 3],
    'values': [
        '32,4;12,4|36,8;14,1|38,1;15',
        '10,15;16,3579|11,9;20,537',
        '1,5;2,1|1,8;2,4|1,9;2,9'
    ]
})

# 可选:去除values列首尾多余空格,避免拆分出空值
df['values'] = df['values'].str.strip()

# 按|和;拆分并扩展为多列
split_cols = df['values'].str.split(r'[|;]', expand=True)
# 重命名列名为column1、column2...格式
split_cols.columns = [f'column{i+1}' for i in range(split_cols.shape[1])]

# 合并id列,得到最终结果
result = pd.concat([df['id'], split_cols], axis=1)

# 可选:将默认的NaN缺失值替换为字符串'NULL'
# result = result.fillna('NULL')

print(result)

输出验证

运行代码后得到的result结构完全符合需求:

idcolumn1column2column3column4column5column6
132,412,436,814,138,115
210,1516,357911,920,537NaNNaN
31,52,11,82,41,92,9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 17:06:03