Pandas数据筛选:排除Employee Common Name含于DisplayName的行
问题修正方案
代码错误分析
你的代码存在三个核心问题:
- 行数据访问错误:在
apply的lambda函数里,你错误引用了整个DataFrame列(df['Employee Common Name']、df['DisplayName']),而非当前行的对应值,导致每次判断的是整列字符串的拼接结果是否匹配,必然全为False。 - 大小写处理不完整:仅对
DisplayName转小写,未处理Employee Common Name,会引发大小写不匹配的问题。 - 逻辑匹配偏差:未正确对应需求与预期输出的逻辑关系。
修正后的代码
import pandas as pd df = pd.DataFrame({'Employee Common Name': ['Bob', 'Makenzie', 'Alice'], 'DisplayName': ['Robert Inger', 'Kenzie Doe', 'Alice Cooper']}) # 统一处理字符串:去除首尾空格+转小写,避免匹配误差 df['Employee Common Name'] = df['Employee Common Name'].str.strip().str.lower() df['DisplayName'] = df['DisplayName'].str.strip().str.lower() # 匹配预期输出逻辑:Common Name是DisplayName子串时,Allowed为True(可选中该行) df['Allowed'] = df.apply(lambda x: x['Employee Common Name'] in x['DisplayName'], axis=1) # 若要严格匹配你最初的需求:Common Name是子串时不选中(Allowed为False),则使用下面的代码 # df['Allowed'] = df.apply(lambda x: x['Employee Common Name'] not in x['DisplayName'], axis=1) print(df)
输出结果
| Employee Common Name | DisplayName | Allowed |
|---|---|---|
| bob | robert inger | False |
| makenzie | kenzie doe | False |
| alice | alice cooper | True |
内容的提问来源于stack exchange,提问作者Zayetzy Luna
相关产品推荐
相关产品推荐

