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

如何在Pandas DataFrame中替换字符串值为列表?

使用Pandas.replace()将字符串替换为列表时出现TypeError的解决方法

我尝试用.split()生成的列表替换Pandas DataFrame里的现有值,但一直报错:TypeError: Invalid "to_replace" type: 'str'。试了好几种相关方案都没用,搞不懂为啥会拒绝我的输入——明明很多方案都在to_replace参数里用字符串啊。

示例数据

idfile_no
102-3234
2 303-3453
03-3454
400-3562
5 6 702-5563
02-5564
02-5565

期望结果

idfile_no
102-3234
[2, 3]03-3453
03-3454
400-3562
[5, 6, 7]02-5563
02-5564
02-5565

当前代码

for id_ in table['id']:
    if len(id_.split(" ")) == 1:
        continue
    elif len(id_.split(" ")) == 2:
        id_split = id_.split(" ")
        table['id'] = table['id'].replace(id_, id_split)                               
    elif len(id_.split(" ")) == 3:
        id_split = id_.split(" ")
        table['id'] = table['id'].replace(id_, id_split)                         
    else:
        continue

问题原因与解决方法

问题根源

Pandas的replace()方法在处理单个值替换为列表时会触发这个错误,因为默认情况下replace()期望替换值的类型和原列类型匹配,而原列是字符串类型,直接传列表会导致类型不兼容。另外,你用循环遍历每一行的写法效率极低,也不符合Pandas的矢量化操作思路。

正确实现方式

不需要循环,直接用矢量化的apply()方法处理整个列:

import pandas as pd

# 构造示例数据(已有DataFrame可跳过)
data = {
    'id': ['1', '2 3', '4', '5 6 7'],
    'file_no': ['02-3234', '03-3453\n03-3454', '00-3562', '02-5563\n02-5564\n02-5565']
}
table = pd.DataFrame(data)

# 将多空格分隔的id转为列表格式的字符串
table['id'] = table['id'].apply(
    lambda x: str([int(num) for num in x.split()]) if len(x.split()) > 1 else x
)

print(table)

代码说明

  1. 矢量化操作:用apply()一次性处理整个列,避免循环遍历的低效问题。
  2. 类型兼容:先把分割后的字符串转成整数,再转成列表格式的字符串,确保和原列的字符串类型匹配,不会触发类型错误。
  3. 条件过滤:只有当分割后的元素数量大于1时才处理,否则保留原值。

如果需要把列存储为实际的列表(而非列表格式的字符串),可以去掉str():

table['id'] = table['id'].apply(
    lambda x: [int(num) for num in x.split()] if len(x.split()) > 1 else x
)

这种情况下列的类型会变为object,存储混合类型(字符串和列表),后续操作需要注意类型兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:37:45