簡體   English   中英

在熊貓數據框中解析/拆分URL的Python方式

[英]pythonic way to parse/split URLs in a pandas dataframe

我有一個df,在標記為url的列中有成千上萬的鏈接(例如以下鏈接)針對不同的用戶:

https://www.google.com/something
https://mail.google.com/anohtersomething
https://calendar.google.com/somethingelse
https://www.amazon.com/yetanotherthing

我有以下代碼:

import urlparse

df['domain'] = ''
df['protocol'] = ''
df['domain'] = ''
df['path'] = ''
df['query'] = ''
df['fragment'] = ''
unique_urls = df.url.unique()
l = len(unique_urls)
i=0
for url in unique_urls:
    i+=1
    print "\r%d / %d" %(i, l),
    split = urlparse.urlsplit(url)
    row_index = df.url == url
    df.loc[row_index, 'protocol'] = split.scheme
    df.loc[row_index, 'domain'] = split.netloc
    df.loc[row_index, 'path'] = split.path
    df.loc[row_index, 'query'] = split.query
    df.loc[row_index, 'fragment'] = split.fragment

該代碼能夠正確解析和拆分網址,但是由於我要遍歷df的每一行,所以它的速度很慢。 有沒有更有效的方法來解析URL?

您可以使用Series.map在一行中完成相同操作:

df['protocol'],df['domain'],df['path'],df['query'],df['fragment'] = zip(*df['url'].map(urlparse.urlsplit))

使用timeit,當在186個URL上運行時,每個循環運行2.31 ms ,而不是原始方法中的每個循環179 ms (但是請注意,代碼並未針對重復項進行優化,並且會在urlparse多次運行相同的url。)

完整代碼:

import pandas

urls = ['https://www.google.com/something','https://mail.google.com/anohtersomething','https://www.amazon.com/yetanotherthing'] # tested with list of 186 urls instead
df['protocol'],df['domain'],df['path'],df['query'],df['fragment'] = zip(*df['url'].map(urlparse.urlsplit))

我認為當您寫回df時,發生了太多的查詢。 看起來每個df.loc[row_index, ...]需要檢查的行數與您獲得的url總數( df.url大小)一樣多。 這意味着,您首先至少要查看所有行以查找唯一的url,然后再次針對每個url查找匹配的行,然后再次針對每次寫入。 因此,假設“ unique僅需進行一次完整掃描,則您將平均掃描表1+N+(5N/2)次。 您實際上只需要一次。

除非您有大量的重復,否則您可以忽略重復項,逐行遍歷df ,並確保每次迭代都使用整數索引。 .iloc )如果不在行中存儲其他數據,還可以一次分配所有字段:

df.iloc[idx] = {'protocol': ..., 'domain': ..., ...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM