python - 使用 str.contains 后合并两个数据框?
问题描述
我有两个数据框,我想通过使用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
我也想合并data1
,data2
这样可以帮助我知道哪些电子邮件匹配。
我想要以下输出:
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
有什么办法吗?
解决方案
如果您擅长仅匹配完整的单词,则可以这样做(例如dog
,dogs
不会匹配)
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(...)
过滤掉那些不匹配的问题。
推荐阅读
- java - 如何将本机查询结果映射到自定义类对象?
- excel - 试图制作一个公式来识别另一个是否为空白,然后添加一个数字 [Excel]
- python - 在同一前缀上注册多个 restplus 蓝图不起作用
- apache-camel - 防止 Apache AHC 向请求中添加“transfer-encoding:chunked”标头
- vue.js - 在 axios 调用时,DOM 不显示 vue.js 和 laravel 中数组的更新数据
- python - 如何找到将列拆分为两个新行的行?
- javascript - 无法在 javascript 中的模块外使用 import 语句
- algorithm - 需要帮助模拟基本导弹 - 目标模拟(算法 - 首选 Qbasic)
- git - git rebase -i HEAD~2 的问题
- graphql - 如何从 graphql 查询的 Contentful 内容类型获取 SYS 数据?