dfs中基于部分字符串匹配的合并

2024-06-24 13:25:16 发布

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

我有一个像这样的df

first_name last_name
John       Doe
Kelly      Stevens
Dorey      Chang

另一个看起来像这样

name             email
John Doe         jdoe23@gmail.com
Kelly M Stevens  kelly.stevens@hotmail.com
D Chang          chang79@yahoo.com

合并这两个表,以便最终结果是

first_name last_name email
    John   Doe       jdoe23@gmail.com
    Kelly  Stevens   kelly.stevens@hotmail.com
    Dorey  Chang     chang79@yahoo.com

我不能按姓名合并,但所有电子邮件都包含每个人的姓氏,即使整体格式不同。有没有办法只使用部分字符串匹配来合并它们?你知道吗

我尝试过这样的事情,但没有成功:

df1['email']= df2[df2['email'].str.contains(df['last_name'])==True]

Tags: namecomdfemailjohngmailfirstlast
1条回答
网友
1楼 · 发布于 2024-06-24 13:25:16

IIUC,您可以对提取的结果使用merge

df1.merge(df2.assign(last_name=df2['name'].str.extract(' (\w+)$'))
             .drop('name', axis=1),
          on='last_name',
          how='left')

输出:

  first_name last_name                      email
0       John       Doe           jdoe23@gmail.com
1      Kelly   Stevens  kelly.stevens@hotmail.com
2      Dorey     Chang          chang79@yahoo.com

相关问题 更多 >