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

Python 在dfs中基于部分字符串匹配的合并,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个像这样的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

我有一个像这样的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
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]

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

如果两个人的姓氏相同怎么办?有没有办法只使用df1中的姓氏列?df2通常比较混乱,虽然这种合并主要起作用,但由于连字符、错误字符等原因,有些行不起作用。