![](/img/trans.png)
[英]pandas insert or join or merge two tables by comparing multiple conditions?
[英]Join two pandas tables on multiple strings
我有两个 pandas dataframe:df1 和 df2。 df1 包含客户的多封电子邮件,我想将其与 df2 匹配,通过查看 df1 中是否存在任何电子邮件在 df2 中来查看有多少客户与公司进行了测试。
我尝试使用.str.split(",", expand=True)
来拆分 email id,并使用pd.merge
加入多个 email id,但它太长了。 在这里发布它以找到更好的解决方案。
df1
myid emails price
1001 pikachu@icloud.com;charizard@gmail.com 1
1002 bulbasaur@gmail.com 2
1003 meowth@gmail.com;james@yahoo.com;jesse@yahoo.com;wobbuffet@yahoo.com 8
1004 abra@gmail.com;ash@yahoo.com 7
1005 squirtle@gmail.com 9
df2
tr_id latest_em test
101 pichu@icloud.com; paul@gmail.com 12
102 ash@yahoo.com 13
103 squirtle@gmail.com 16
104 charmander@gmail.com 18
105 ash@yahoo.com;misty@yahoo.com 10
预期 Output:
myid emails price tr_id latest_em test
1004 abra@gmail.com;ash@yahoo.com 7 102 ash@yahoo.com 13
1004 abra@gmail.com;ash@yahoo.com 7 105 ash@yahoo.com;misty@yahoo.com 10
1005 squirtle@gmail.com 9 103 squirtle@gmail.com 16
(df1
.assign(key=df1['emails'].str.split(';\s*')).explode('key')
.merge(df2.assign(key=df2['latest_em'].str.split(';\s*')).explode('key'),
on='key'
)
.drop(columns='key')
)
output:
myid emails price tr_id latest_em test
0 1004 abra@gmail.com;ash@yahoo.com 7 102 ash@yahoo.com 13
1 1004 abra@gmail.com;ash@yahoo.com 7 105 ash@yahoo.com;misty@yahoo.com 10
2 1005 squirtle@gmail.com 9 103 squirtle@gmail.com 16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.