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

pandas如何删除DataFrame某列中存在于另一列的对应行文本

问题解决方案

报错原因

Series.str.replace()方法的第一个入参要求为固定字符串或正则表达式模式,不支持直接传入另一个Series实现逐行匹配替换,因此会抛出'Series' objects are mutable, thus they cannot be hashed异常。

最优实现方案

针对10000行级别的数据集,列表推导式是性能最优的轻量化方案,耗时仅为毫秒级,远快于普通for循环:

# 逐行替换,.strip()用于去除替换后首尾多余的空格
df['Result'] = [full.replace(remove, '').strip() for full, remove in zip(df['Full Name'], df['TextToRemove'])]

如果偏好pandas原生写法,也可以使用逐行apply实现,性能略低于列表推导式,但对10000行数据也完全够用:

df['Result'] = df.apply(lambda row: row['Full Name'].replace(row['TextToRemove'], '').strip(), axis=1)

输出效果验证

以你提供的第0行数据为例,运行后得到的Result列值即为预期的Active Auto MY16。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:36:06