我有csv (或dataframe)的内容如下:
date | URLs | Count
-----------------------------------------------------------------------
17-mar-2014 | www.example.com/abcdef&=randstring | 20
10-mar-2016 | www.example.com/xyzabc | 12
14-apr-2015 | www.example.com/abcdef | 11
12-mar-2016 | www.example.com/abcdef/randstring | 30
15-mar-2016 | www.example.com/abcdef | 10
17-feb-2016 | www.example.com/xyzabc&=randstring | 15
17-mar-2016 | www.example.com/abcdef&=someotherrandstring | 12我想清除列'URLs‘,其中我想将所有行的www.example.com/abcdef&=randstring或www.example.com/abcdef/randstring转换为www.example.com/abcdef等等。
我试着使用urlparse库,并解析URL,将urlparse(url).netloc与urlparse结合起来。但是,由于每个URL都会导致完全不同的路径/查询/params,所以它被调整为效率低下。
有什么工作可以利用熊猫吗?如有任何提示或建议,将不胜感激。
发布于 2016-12-14 11:37:56
我认为它与regex的关系比熊猫更多,尝试使用pandas.apply来更改一个列。
import pandas as pd
import re
def clear_url(origin_url):
p = re.compile('(www.example.com/[a-zA-Z]*)')
r = p.search(origin_url)
if r:
return r.groups(1)[0]
else:
return origin_url
d = [
{'id':1, 'url':'www.example.com/abcdef&=randstring'},
{'id':2, 'url':'www.example.com/abcdef'},
{'id':3, 'url':'www.example.com/xyzabc&=randstring'}
]
df = pd.DataFrame(d)
print 'origin_df'
print df
df['url'] = df['url'].apply(clear_url)
print 'new_df'
print df输出:
origin_df
id url
0 1 www.example.com/abcdef&=randstring
1 2 www.example.com/abcdef
2 3 www.example.com/xyzabc&=randstring
new_df
id url
0 1 www.example.com/abcdef
1 2 www.example.com/abcdef
2 3 www.example.com/xyzabc发布于 2016-12-14 11:28:08
我认为您可以使用extract by regex - filter由a-z和A-Z在www和.com之间创建的所有字符串,以及另一个以/开头的字符串。
print (df.URLs.str.extract('(www.[a-zA-Z]*.com/[a-zA-Z]*)', expand=False))
0 www.example.com/abcdef
1 www.example.com/xyzabc
2 www.example.com/abcdef
3 www.example.com/abcdef
4 www.example.com/abcdef
5 www.example.com/xyzabc
6 www.example.com/abcdef
Name: URLs, dtype: objecthttps://stackoverflow.com/questions/41141265
复制相似问题