Python Pandas文本替换与列比较报错求助:unsupported operand type错误
解决Pandas字符串替换中的
|操作符错误 你的报错原因很明确:代码里把两个字符串直接用|运算了,而Python字符串不支持这种操作。具体来说,'\.'|' (On Leave)'这部分写法错误,你想表达的是正则里的“或”逻辑,但不能把两个字符串分开用|连接,必须把整个正则规则放在一个字符串里。
修正后的代码
先直接给你可以运行的修正版本,再一步步解释:
import pandas as pd # 测试数据 data = { 'PrimaryColumn': ['Mr', 'Jr', 'Mrs', 'Mr', 'Mr', 'Mr'], 'SecondaryColumn': ['Mr.', 'Jr', 'Mrs', 'Mrs', 'Mr (On Leave)', 'NOTAPPLICABLEHERE'] } temp_result_df = pd.DataFrame(data) # 定义变量 primaryreportreqcolname = 'PrimaryColumn' RequiredSecondaryReport_Col_Name = 'SecondaryColumn' res_col_name = 'ExpectedOutput' Exceptions = "NOTAPPLICABLEHERE" # 核心修正代码 temp_result_df[res_col_name] = ( # 匹配Primary列和清洗后的Secondary列 temp_result_df[primaryreportreqcolname].eq( temp_result_df[RequiredSecondaryReport_Col_Name].str.replace( r'\.| \(On Leave\)', '', regex=True ) ) # 或匹配例外值 | (temp_result_df[RequiredSecondaryReport_Col_Name] == Exceptions) ) print(temp_result_df)
关键修正点
正则表达式写法修正
把原来分开的'\.'|' (On Leave)'改成r'\.| \(On Leave\)':- 用原始字符串前缀
r:避免转义字符的混乱,让正则更易读。 - 把两个匹配规则合并到一个字符串里:用
|分隔“匹配点号”和“匹配(On Leave)”两个规则。 - 转义括号:
()在正则里是分组符号,要匹配字面的括号必须写成\(和\)。
- 用原始字符串前缀
括号明确运算优先级
虽然Pandas的eq优先级比|高,但给每个布尔条件加上括号,能让代码逻辑更清晰,避免潜在的运算顺序问题。
运行结果
执行后会得到和你预期完全一致的输出:
PrimaryColumn SecondaryColumn ExpectedOutput 0 Mr Mr. True 1 Jr Jr True 2 Mrs Mrs True 3 Mr Mrs False 4 Mr Mr (On Leave) True 5 Mr NOTAPPLICABLEHERE True
内容的提问来源于stack exchange,提问作者Student of the Digital World
相关产品推荐
相关产品推荐

