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

使用Pandas基于其他列动态替换值提取Model列

解决Pandas逐行基于其他列替换字符串的问题

你遇到的unhashable type: 'Series'错误,是因为str.replace的第一个参数只接受单个字符串/正则表达式,不能直接传入整个Series(逐行变量)。下面是几种可行的逐行处理方案:

方法1:用apply逐行处理(直观易读)

通过apply按行遍历,对每行单独执行替换操作:

df['Model'] = df.apply(
    lambda row: row['Car'].replace(row['Make'], '').replace(row['Engine'], '').strip(),
    axis=1
)

如果要确保只替换开头的Make和结尾的Engine(避免中间出现相同字符串被误替换),可以结合正则处理:

import re

df['Model'] = df.apply(
    lambda row: re.sub(f'^{re.escape(row["Make"])}', '', row['Car'])
                  .removesuffix(row['Engine'])
                  .strip(),
    axis=1
)

re.escape用来转义Make/Engine里的特殊正则字符(比如.、*),避免语法错误。

方法2:列表推导式(性能优于apply)

用列表推导直接遍历每行数据执行替换,速度比apply更快:

import re

df['Model'] = [
    car.replace(re.escape(make), '').replace(re.escape(engine), '').strip()
    for car, make, engine in zip(df['Car'], df['Make'], df['Engine'])
]

方法3:字符串切片(仅适用于固定拼接顺序)

如果你的Car列严格遵循[Make][空格][Model][空格][Engine]的拼接顺序(Make在最开头,Engine在最末尾),可以用切片操作,效率最高:

# 先切掉开头的Make部分,再切掉结尾的Engine部分,最后去首尾空格
df['Model'] = df['Car'].str[df['Make'].str.len():].str[:-df['Engine'].str.len()].str.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:05:21