
本文旨在介绍如何使用 Pandas 判断 DataFrame 中两列字符串值是否相互包含,并生成一个新的布尔列来标识匹配结果。通过结合 `numpy.where` 和字符串 `in` 运算符,我们可以高效地实现此功能,并处理可能存在的缺失值情况。
在数据处理过程中,经常会遇到需要判断 DataFrame 中不同列的字符串值是否相互包含的情况。例如,判断产品名称是否包含在产品描述中,或者判断客户名称是否包含在客户地址中。本文将介绍如何使用 Pandas 和 NumPy 来高效地实现这一功能。
方法:使用 numpy.where 和 in 运算符
核心思路是使用 NumPy 的 where 函数,结合 Python 的 in 运算符,逐行判断两列字符串是否相互包含。为了处理可能存在的缺失值(NaN),我们需要先使用 fillna 方法填充缺失值。
示例代码
假设我们有如下 DataFrame:
import pandas as pd
import numpy as np
data = {'Column1': ['Customer1', np.nan, 'Customer3', np.nan, 'Customer5 LLC', 'Customer6 LLC', np.nan, np.nan],
'Column2': ['Customer1', 'Customer2', np.nan, 'Customer4 LLC', np.nan, np.nan, 'Customer9 LLC', np.nan],
'Match_Column': ['Customer1 LLC', 'Customer2 LLC', 'Customer3 LLC', 'Customer4', 'Customer5', 'Customer8', 'Customer4', 'Customer4']}
df = pd.DataFrame(data)
print(df)输出:
Column1 Column2 Match_Column 0 Customer1 Customer1 Customer1 LLC 1 NaN Customer2 Customer2 LLC 2 Customer3 NaN Customer3 LLC 3 NaN Customer4 LLC Customer4 4 Customer5 LLC NaN Customer5 5 Customer6 LLC NaN Customer8 6 NaN Customer9 LLC Customer4 7 NaN NaN Customer4
现在,我们想要判断 Column1 或 Column2 中的值是否包含在 Match_Column 中,或者 Match_Column 中的值是否包含在 Column1 或 Column2 中。可以使用以下代码实现:
df['is_Match'] = np.where([(a in c) or (b in c) or (c in a) or (c in b) for a,b,c
in zip(df['Column1'].fillna('_'), df['Column2'].fillna('_'),
df['Match_Column'].fillna('nodata'))],
'Yes', 'No')
print (df)输出:
Column1 Column2 Match_Column is_Match 0 Customer1 Customer1 Customer1 LLC Yes 1 NaN Customer2 Customer2 LLC Yes 2 Customer3 NaN Customer3 LLC Yes 3 NaN Customer4 LLC Customer4 Yes 4 Customer5 LLC NaN Customer5 Yes 5 Customer6 LLC NaN Customer8 No 6 NaN Customer9 LLC Customer4 No 7 NaN NaN Customer4 No
代码解释
- df['Column1'].fillna('_'): 使用 fillna('_') 将 Column1 中的缺失值替换为 '_'。这样做是为了避免在后续的字符串比较中出现错误。
- df['Column2'].fillna('_'): 同样,使用 fillna('_') 将 Column2 中的缺失值替换为 '_'。
- df['Match_Column'].fillna('nodata'): 使用 fillna('nodata') 将 Match_Column 中的缺失值替换为 'nodata'。
- zip(df['Column1'].fillna('_'), df['Column2'].fillna('_'), df['Match_Column'].fillna('nodata')): 使用 zip 函数将三个列的值逐行打包成元组。
- [(a in c) or (b in c) or (c in a) or (c in b) for a,b,c in ...]: 这是一个列表推导式,它遍历 zip 函数生成的元组,对于每个元组 (a, b, c),判断 a 是否包含在 c 中,或者 b 是否包含在 c 中,或者 c 是否包含在 a 中,或者 c 是否包含在 b 中。如果其中一个条件成立,则返回 True,否则返回 False。
- np.where(..., 'Yes', 'No'): numpy.where 函数根据列表推导式的结果,如果为 True,则返回 'Yes',否则返回 'No'。
注意事项
- 缺失值处理: 在进行字符串比较之前,务必处理缺失值,否则可能会导致错误。
- 性能: 对于大型 DataFrame,使用循环可能会比较慢。可以考虑使用向量化的字符串操作来提高性能。
- 大小写敏感: 默认情况下,字符串比较是大小写敏感的。如果需要进行大小写不敏感的比较,可以使用 lower() 方法将字符串转换为小写。
总结
本文介绍了如何使用 Pandas 和 NumPy 来判断 DataFrame 中两列字符串值是否相互包含。通过结合 numpy.where 和 in 运算符,我们可以高效地实现此功能,并处理可能存在的缺失值情况。这种方法在数据清洗、特征工程等场景中非常有用。










