使用pandas str.replace时出现TypeError: unhashable type: 'Series'错误
解决Pandas逐行移除对应子字符串的报错问题
报错原因
你的代码触发TypeError: unhashable type: 'Series',是因为pandas.Series.str.replace()方法的第一个参数要求是单个字符串或正则表达式,而非Pandas Series。直接传入Series时,Python会尝试将其作为哈希对象处理,导致错误。
解决方案
方法1:用apply逐行执行字符串替换
这是最直接的逐行处理方式:
import pandas as pd df = pd.DataFrame( { "substring": ["This", "sentence."], "id": [1, 1], "string": ["This is a sentence.", "This is another sentence."], } ) # 逐行替换对应子字符串 df["replaced"] = df.apply(lambda row: row["string"].replace(row["substring"], ""), axis=1)
执行后replaced列结果为:
0 is a sentence. 1 This is another
方法2:支持正则替换(含特殊字符转义)
如果你的子字符串包含正则特殊字符(比如示例中的.),需要用re.sub并配合re.escape转义,避免特殊字符干扰替换逻辑:
import pandas as pd import re df = pd.DataFrame( { "substring": ["This", "sentence."], "id": [1, 1], "string": ["This is a sentence.", "This is another sentence."], } ) # 转义正则特殊字符后逐行替换 df["replaced"] = df.apply(lambda row: re.sub(re.escape(row["substring"]), "", row["string"]), axis=1)
原代码失效原因
str.replace()是向量化方法,它会将第一个参数视为全局统一的替换目标,而非逐行匹配对应列的子字符串。传入Series不符合方法参数要求,因此触发哈希错误。
内容的提问来源于stack exchange,提问作者Blob
相关产品推荐
相关产品推荐

