如何用字典替换Pandas列名中的多个子串?代码失效问题排查
解决Pandas列名子串批量替换问题
问题根源
你用的df.rename(columns=...)是完全匹配整列列名后替换,没法识别列名里的子串,所以达不到预期的局部替换效果。要替换子串,得用Pandas的字符串处理方法str.replace(),还能按指定顺序执行替换逻辑。
修正后的代码
# 按顺序执行替换:先修复编码错误的单引号,再替换I'm为I am,最后替换this company为Company df2.columns = df2.columns.str.replace("’", "'")\ .str.replace("I'm", "I am")\ .str.replace("this company", "Company")
代码逻辑说明
- 第一步
str.replace("’", "'"):把编码乱码的’替换成正常单引号',所有I’m会自动变成I'm - 第二步
str.replace("I'm", "I am"):把所有出现的I'm替换成I am - 第三步
str.replace("this company", "Company"):把列名里的this company替换成Company
实际效果验证
用你给出的列名测试:
- 原列名:
I understand how my job contributes to the overall success of this company .
替换后:I understand how my job contributes to the overall success of Company . - 原列名:
I get enough feedback to understand if I’m doing my job well .
替换后:I get enough feedback to understand if I am doing my job well . - 原列名:
I'm satisfied with the amount of flexibility I have in my work schedule .
替换后:I am satisfied with the amount of flexibility I have in my work schedule .
可维护性优化方案
如果后续要加更多替换规则,把规则放到列表里循环执行更方便:
replace_rules = [ ("’", "'"), ("I'm", "I am"), ("this company", "Company") ] for old_str, new_str in replace_rules: df2.columns = df2.columns.str.replace(old_str, new_str)
后续新增替换需求,直接往列表里加元组就行。
内容的提问来源于stack exchange,提问作者Scythor
相关产品推荐
相关产品推荐

