2025年03月03日 Python DataFrame 如何判断一列字符串在另一列中 极客笔记
在处理数据时,经常会遇到需要判断一个列中的字符串是否包含在另一个列中的情况。在Python中,我们通常会使用pandas库来处理数据,并且pandas提供了一种简单而有效的方法来实现这一目标。本文将介绍如何使用pandas DataFrame来判断一列字符串是否包含在另一列中。
首先,让我们创建一个示例DataFrame来展示如何进行字符串的包含判断。我们可以使用以下代码创建一个包含两列的DataFrame,其中一列是包含字符串的列,另一列是我们要检查是否包含的列。
import pandas as pd
data = {
'column1': ['apple', 'banana', 'cherry', 'orange', 'mango'],
'column2': ['apple pie', 'grape', 'cherry tart', 'orange juice', 'mango smoothie']
}
df = pd.DataFrame(data)
print(df)
运行以上代码,我们将得到如下的DataFrame:
column1 column2
0 apple apple pie
1 banana grape
2 cherry cherry tart
3 orange orange juice
4 mango mango smoothie
在这个示例DataFrame中,我们的目标是判断column1
中的字符串是否在column2
中。
为了判断一列中的字符串是否包含在另一列中,我们可以使用str.contains()
方法。这个方法可以在pandas的Series对象上直接调用,用来检查每个元素是否包含指定的子字符串。接下来,让我们看看如何使用str.contains()
方法来判断column1
中的字符串是否在column2
中。
df['contains'] = df['column2'].str.contains('|'.join(df['column1']), case=False)
print(df)
在上面的代码中,我们首先使用'|'.join(df['column1'])
将column1
中的所有字符串以|
连接成一个正则表达式的形式,用来指定我们要查找的子字符串。然后我们调用str.contains()
方法,将结果存储在一个新的列contains
中。
运行以上代码,我们将得到如下的DataFrame:
column1 column2 contains
0 apple apple pie True
1 banana grape False
2 cherry cherry tart True
3 orange orange juice True
4 mango mango smoothie True
从上面的输出可以看出,column1
中的字符串是否在column2
中的判断结果已经存储在了contains
列中。
在实际应用中,我们可能经常需要根据一个列中的关键词是否包含在另一个列的文本中来进行条件筛选或者数据处理。比如,我们可以根据contains
列的结果来筛选出包含特定关键词的行,或者进行其他进一步的处理。
filtered_df = df[df['contains']]
print(filtered_df)
以上代码将会筛选出contains
列为True
的那些行,也就是column1
中的字符串在column2
中的那些行。运行以上代码,我们将得到如下的DataFrame:
column1 column2 contains
0 apple apple pie True
2 cherry cherry tart True
3 orange orange juice True
4 mango mango smoothie True
通过使用pandas DataFrame的str.contains()
方法,我们可以轻松地判断一列字符串是否包含在另一列中。这种方法在数据处理和分析中非常实用,能够帮助我们快速得到符合条件的数据行,或者进行其他进一步的处理。
本文链接:http://so.lmcjl.com/news/24227/