![](/img/trans.png)
[英]How to add “https://www.” into your scraping result with python?
[英]How to add 'www.' to the beginning of some dataframe values?
我有包含域名的數據:
url var1
www.google.com xsd
ebay.com wer
www.amazon.com xyz
microsoft.com zyx
....
我需要添加'www。' 到開頭沒有它的域名。
我有這個代碼:
try:
for domain in df['url']:
if domain.startswith('www.'):
next
else:
domain = 'www.' + domain.astype(str)
except ConnectionResetError:
print('Handle Exception')
代碼生成錯誤:
AttributeError: 'str' object has no attribute 'astype'
我究竟做錯了什么?
當你可以在所有行上map()
函數時,不要使用循環。
def prefixWWW(url):
return 'www.' + url if not url.startswith('www.') else url
df = df['url'].map(prefixWWW)
我這樣做:
In [235]: df.loc[~df.url.str.contains(r'^www\.'), 'url'] = \
'www' + df.loc[~df.url.str.contains(r'^www\.'), 'url']
In [236]: df
Out[236]:
url var1
0 www.google.com xsd
1 wwwebay.com wer
2 www.amazon.com xyz
3 wwwmicrosoft.com zyx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.