如何在Pandas中双向检查列值是否包含另一列值
处理Pandas DataFrame字符串列的双向包含匹配问题
需求很明确:要给DataFrame新增is_Match列,标记每一行的Column1或Column2是否与Match_Column存在双向包含关系——要么前者是后者的子串,要么后者是前者的子串。
示例输入数据
Column1 | Column2 | Match_Column --------------------------------------------- Customer1 | Customer1 | Customer1 LLC | Customer2 | Customer2 LLC Customer3 | | Customer3 LLC | Customer4 LLC | Customer4 Customer5 LLC | | Customer5 Customer6 LLC | | Customer8 | Customer9 LLC | Customer4
预期输出
Column1 | Column2 | Match_Column | is_Match ---------------------------------------------------------- Customer1 | Customer1 | Customer1 LLC | Yes NaN | Customer2 | Customer2 LLC | Yes Customer3 | NaN | Customer3 LLC | Yes NaN | Customer4 LLC | Customer4 | Yes Customer5 LLC | NaN | Customer5 | Yes Customer6 LLC | NaN | Customer8 | No NaN | Customer9 LLC | Customer4 | No NaN | NaN | Customer4 | No
你之前代码的问题
你用的isin()是检查整个字符串是否存在于另一列的元素列表中,但我们需要的是子串包含匹配,所以这个方法完全不适用,自然得不到预期结果。
正确解决方案
我们需要逐行检查字符串的包含关系,步骤如下:
- 先把DataFrame里的空值(NaN)替换成空字符串,避免后续字符串操作报错
- 定义一个辅助函数,判断两个字符串是否存在双向包含关系
- 对每一行,检查
Column1与Match_Column、Column2与Match_Column中任意一对满足包含关系,就标记为Yes,否则No
完整代码
import pandas as pd # 构造示例数据 data = { 'Column1': ['Customer1', None, 'Customer3', None, 'Customer5 LLC', 'Customer6 LLC', None, None], 'Column2': ['Customer1', 'Customer2', None, 'Customer4 LLC', None, None, 'Customer9 LLC', None], 'Match_Column': ['Customer1 LLC', 'Customer2 LLC', 'Customer3 LLC', 'Customer4', 'Customer5', 'Customer8', 'Customer4', 'Customer4'] } df = pd.DataFrame(data) # 1. 替换NaN为空字符串 df = df.fillna('') # 2. 定义双向包含检查函数 def check_match(s1, s2): # 两个都为空的情况直接返回False if not s1 and not s2: return False return s1 in s2 or s2 in s1 # 3. 应用函数生成is_Match列 df['is_Match'] = df.apply(lambda row: 'Yes' if check_match(row['Column1'], row['Match_Column']) or check_match(row['Column2'], row['Match_Column']) else 'No', axis=1) print(df)
代码说明
fillna(''):把所有NaN转成空字符串,避免后续in操作时抛出异常check_match函数:先排除两个都为空的情况(对应最后一行的场景),然后判断两个字符串是否互相包含apply(axis=1):逐行处理数据,检查Column1/Column2与Match_Column的匹配情况,生成结果
运行这段代码后,就能得到你想要的预期输出。
内容的提问来源于stack exchange,提问作者Hari Shreyas
相关产品推荐
相关产品推荐

