gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:49:59 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 基于pandas dfs中部分字符串匹配的合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59534955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com