首页 > 解决方案 > 使用 str.contains 后合并两个数据框?

问题描述

我有两个数据框,我想通过使用str.contains函数来匹配部分字符串,然后合并它们。

这是一个例子:

data1

      email     is_mane         name           id
    hi@amal.com     1   there is rain          10
    hi2@amal.com    1   here is the food        9
    hi3@amal.com    1   let's go together       8
    hi4@amal.com    1   today is my birthday    6


data2

    id  name
    1   the rain is beautiful
    1   the food
    2   together
    4   my birthday
    3   your birthday

这是我写的代码:

data.loc[data.name.str.contains('|'.join(data2.name)),:]

和输出:

        email   is_mane     name               id
    hi2@amal.com    1   here is the food        9
    hi3@amal.com    1   let's go together       8
    hi4@amal.com    1   today is my birthday    6

如您所见,即使该词包含在中,它也没有返回“有雨”:可能是因为空间吗?raindara2

我也想合并data1data2这样可以帮助我知道哪些电子邮件匹配。

我想要以下输出:


        email   is_mane     name               id      id2       name2
    hi2@amal.com    1   here is the food        9       1       the food
    hi3@amal.com    1   let's go together       8       2       together
    hi4@amal.com    1   today is my birthday    6       4       my birthday
    hi4@amal.com    1   today is my birthday    6       3       your birthday

有什么办法吗?

标签: pythonpandas

解决方案


如果您擅长仅匹配完整的单词,则可以这样做(例如dogdogs不会匹配)

data1["key"]=data1["name"].str.split(r"[^\w+]")
data2["key"]=data2["name"].str.split(r"[^\w+]")

data3=data1.explode("key").merge(data2.explode("key"), on="key", suffixes=["", "2"]).drop("key", axis=1).drop_duplicates()

否则,这是一个交叉连接的问题,并申请str.contains(...)过滤掉那些不匹配的问题。


推荐阅读