python-3.x - 如何从 Pandas 数据框中的两列中提取匹配的关键字?

标签 python-3.x pandas dataframe text-extraction

我在数据框中有两列都是字符串,其中 column1 在 column2 中有一些匹配的关键字。我想从新列中的 column1 和 column2 中提取那些匹配的关键字。

df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]

我期待这样的输出

column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color

最佳答案

使用应用

例如:

df["column3"] = df.apply(lambda x: " ".join(i for i in x["column2"].split() if i in x["column1"]),axis=1) 
print(df)

输出:

                     column1                column2         column3
0  A girl is going to market     girl market school     girl market
1  A girl is going to school     girl market school     girl school
2   The sky is blue in color  sky blue orange color  sky blue color

关于python-3.x - 如何从 Pandas 数据框中的两列中提取匹配的关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325012/

相关文章:

r - 数据框列的平均值

python - pandas 使用 LIKE 运算符加入条件

python-3.x - 获取 pandas 数据框中两个给定日期之间的月份的结束日期

python - 将生成器包装为单个 `next` 调用,而不是两个步骤( __iter__ + __next__ )

python - 在 Python3 中操作 JSON 配置文件内变量的最佳方法

python - 为什么我的数组值没有更新?线性回归

python - 索引错误 : single positional indexer is out-of-bounds and if condition

python - 我的时间戳字符串末尾有 "-05:00",这是什么意思,我该如何处理?

python - 如何使用列作为索引获取 pandas 数据框中某个位置的单元格

python - "New style getargs format but argument is not a tuple"枕头图片粘贴错误