
本文介绍了如何使用 Pandas 和 NumPy 检查 DataFrame 中一列的值是否包含另一列的值,或者反过来。通过 `numpy.where` 结合 `in` 语句,我们可以逐行比较不同列的字符串,判断是否存在包含关系,并生成新的布尔列来指示匹配结果。同时,我们也需要处理缺失值,避免其影响判断结果。
在数据分析和处理中,经常会遇到需要检查一个字符串是否包含在另一个字符串中的情况。尤其是在处理文本数据时,例如,判断一个公司名称是否包含在另一个公司名称的缩写中,或者判断一个产品名称是否包含在描述信息中。Pandas 提供了强大的数据处理能力,结合 NumPy 可以高效地完成这类任务。
问题描述
假设我们有一个 Pandas DataFrame,其中包含三列:Column1、Column2 和 Match_Column。我们的目标是创建一个新的列 is_Match,该列的值为 'Yes' 或 'No',取决于以下条件:
立即进入“豆包AI人工智官网入口”;
立即学习“豆包AI人工智能在线问答入口”;
如果以上任何一个条件成立,则 is_Match 的值为 'Yes',否则为 'No'。
解决方案
我们可以使用 NumPy 的 where 函数结合 Python 的 in 语句来解决这个问题。numpy.where 函数允许我们基于条件表达式创建新的数组,而 in 语句可以用来判断一个字符串是否包含在另一个字符串中。
以下是具体的代码实现:
import pandas as pd
import numpy as np
# 示例数据
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)
# 使用 numpy.where 和 in 语句创建 is_Match 列
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)代码解释
导入必要的库:
import pandas as pd import numpy as np
导入 Pandas 用于数据处理,NumPy 用于数组操作。
创建示例 DataFrame:
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)创建一个包含示例数据的 DataFrame。注意 DataFrame 中包含缺失值 (None)。
使用 numpy.where 和 in 语句创建 is_Match 列:
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)
打印包含 is_Match 列的 DataFrame。
注意事项
总结
本文介绍了如何使用 Pandas 和 NumPy 检查 DataFrame 中一列的值是否包含另一列的值。通过 numpy.where 结合 in 语句,我们可以高效地完成这类任务。同时,我们也需要注意处理缺失值和字符串大小写,以确保结果的准确性。这种方法在处理文本数据时非常有用,例如,在数据清洗、特征工程和数据分析等场景中。
以上就是Pandas:检查DataFrame中一列的值是否包含另一列的值(反之亦然)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号