Python函数:如果一个数据集中的链接是另一个数据集中链接的一部分,则分配1,else 0
示例数据集我有:
df1:
id | Page链接 |
---|---|
1 | http:// example1/path1/ru/path2/path3 |
2 | https://example2.com/path1 |
3 | https://example3.subdomain |
df2:
id | 链接 |
---|---|
1 | http:/http:/http:/ /example1/path1/ru |
2 | https://example2.com/path1 |
3 | https://example3.subdomain/path2 |
在DF1中,我需要创建一个具有值1或0的列['contains']。如果df1链接是df2中链接的一部分,则['contains'] = 1,否则0
使得最终结果看起来像这样:
DF1
ID | PAGE链接 | 包含 |
---|---|---|
1 | http:// example1/path1/ru/path2/path | 3 1 |
2 | https://example2.com/path1 | 1 |
3 | https://example3.subdomain | 0 |
我尝试了:
def assign(column):
for link in df2['Link']:
if re.search(link, column):
contains=1
else
contains=0
return contains
df1['Contains']=df1['Page Link'].apply(assign)
这没有返回我期望的结果
leads['Marketing Team']=leads['Page Link'].apply(assign_marketing)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用的功能在找到匹配项时不会停止,然后可能会“改变主意”。这是一个固定的版本:
如果匹配始终在开始时,则可以用更快的
startswith()
:The function that you use does not stop when it finds a match, and may later "change its mind." Here is a fixed version:
If the match is always at the beginning, you can replace the expensive
re.search()
with a much fasterstartswith()
:这个问题不是高度明确的,因此,如果您想检查链接匹配 per ID ,则可以使用:
输出:
The question is not highly explicit, so in case you want to check the link match per ID, you can use:
output:
使用 带有正则 - 通过
|
加入值df2.link
带有Escape:如果需要测试,所有链接都使用嵌套列表理解 - 如果两个大数据范围:
Use
Series.str.contains
with regex - join values by|
ofdf2.Link
with escape:If need test all links use nested list comprehension - it should be slow if large both DataFrames: