使用 urllib 解析/拆分 Pandas 数据帧中的 URL [英] Parse/split URLs in a pandas dataframe using urllib

查看:43
本文介绍了使用 urllib 解析/拆分 Pandas 数据帧中的 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试拆分 URL 并将片段放入数据框中.我发现这个线程 pythonic way to parse/split URLs in一个熊猫数据框并尝试应用它,但由于某种原因它给了我一个错误.

I'm trying to split URLs and put the fragments in a dataframe. I found this thread pythonic way to parse/split URLs in a pandas dataframe and try to apply it, but for some reason it gives me an error.

我使用的是 Python 3.x,所以我使用了以下代码:

I am under Python 3.x so I used the following:

import pandas
import urllib

urls = ['https://www.google.com/something','https://mail.google.com/anohtersomething', 'https://www.amazon.com/yetanotherthing']
df['protocol'],df['domain'],df['path'],df['query'],df['fragment'] = zip(*df['url'].map(urllib.parse.urlsplit))

我收到一条错误消息,说 KeyError: 'urls',不知道是什么意思.

I get an error saying KeyError: 'urls', not sure what it means.

如果有人能帮忙就好了.谢谢.

If someone could help would be great. Thanks.

推荐答案

您使用的示例假定链接位于数据框中.这是正确的解决方案:

The example you used assumes that the links are in a dataframe. Here's the correct solution:

import urllib
import pandas as pd

df = pd.DataFrame()
urls = ['https://www.google.com/something','https://mail.google.com/anohtersomething', 'https://www.amazon.com/yetanotherthing']
df['protocol'],df['domain'],df['path'],df['query'],df['fragment'] = zip(*[urllib.parse.urlsplit(x) for x in urls])

结果

  protocol           domain               path query fragment
0    https   www.google.com         /something
1    https  mail.google.com  /anohtersomething
2    https   www.amazon.com   /yetanotherthing

这篇关于使用 urllib 解析/拆分 Pandas 数据帧中的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆