首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在两个Pandas Dataframe列之间查找匹配关键字之前和之后的单词,并在新列中返回

在两个Pandas DataFrame列之间查找匹配关键字之前和之后的单词,并在新列中返回。

首先,我们可以使用正则表达式来查找匹配关键字之前和之后的单词。然后,我们可以将找到的单词存储在一个新的列中。

以下是一种实现的方式:

代码语言:txt
复制
import pandas as pd
import re

def find_words_before_and_after(df, column1, column2, keyword):
    # 创建新列
    df['new_column'] = ""

    # 遍历DataFrame的行
    for index, row in df.iterrows():
        # 获取两个列的值
        text1 = row[column1]
        text2 = row[column2]
        
        # 使用正则表达式查找匹配关键字之前和之后的单词
        pattern = r"\b(\w*{}(?:\w*)?)\b".format(re.escape(keyword))
        matches1 = re.findall(pattern, text1)
        matches2 = re.findall(pattern, text2)
        
        # 拼接找到的单词
        words = " ".join(matches1 + matches2)
        
        # 将单词存储在新列中
        df.at[index, 'new_column'] = words

    return df

# 创建示例DataFrame
df = pd.DataFrame({'text1': ['Hello world', 'This is a test'], 'text2': ['World, hello', 'Test, test']})

# 调用函数查找匹配关键字之前和之后的单词
df = find_words_before_and_after(df, 'text1', 'text2', 'test')

# 打印结果
print(df)

这段代码会在示例DataFrame的基础上,通过调用find_words_before_and_after函数来查找text1text2列中,匹配关键字"test"之前和之后的单词,并将结果存储在新列new_column中。最后,打印出结果DataFrame。

请注意,这只是一种实现方式,根据具体需求,可能有其他更适合的方法或函数可以实现相同的功能。

(关键词:Pandas Dataframe, 列之间查找, 匹配关键字, 单词, 新列, 正则表达式)

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券