
本文旨在介绍如何使用 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
代码解释
注意事项
总结
本文介绍了如何使用 Pandas 和 NumPy 来判断 DataFrame 中两列字符串值是否相互包含。通过结合 numpy.where 和 in 运算符,我们可以高效地实现此功能,并处理可能存在的缺失值情况。这种方法在数据清洗、特征工程等场景中非常有用。
以上就是Pandas 中判断两列字符串值是否相互包含的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号