使用str.contains后合并两个数据帧?

2024-05-29 07:08:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,我想使用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

正如您所看到的,它没有返回“有雨”,即使rain单词包含在dara2中:这可能是因为空间吗

另外,我想将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

有什么办法吗


Tags: thenamecomidtodayfoodisemail
1条回答
网友
1楼 · 发布于 2024-05-29 07:08:44

如果您擅长只匹配完整单词,那么您可以这样做(例如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(...)过滤掉不匹配的部分

相关问题 更多 >

    热门问题