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

Pandas数据筛选:排除Employee Common Name含于DisplayName的行

问题修正方案

代码错误分析

你的代码存在三个核心问题:

  1. 行数据访问错误:在apply的lambda函数里,你错误引用了整个DataFrame列(df['Employee Common Name']、df['DisplayName']),而非当前行的对应值,导致每次判断的是整列字符串的拼接结果是否匹配,必然全为False。
  2. 大小写处理不完整:仅对DisplayName转小写,未处理Employee Common Name,会引发大小写不匹配的问题。
  3. 逻辑匹配偏差:未正确对应需求与预期输出的逻辑关系。

修正后的代码

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 NameDisplayNameAllowed
bobrobert ingerFalse
makenziekenzie doeFalse
alicealice cooperTrue

内容的提问来源于stack exchange,提问作者Zayetzy Luna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:25:09