如何将“www.”添加到某些数据帧值的开头?

2024-06-02 05:08:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有包含域名的数据:

 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'

我做错什么了?你知道吗


Tags: 数据comurlamazondomainwwwgoogle域名
2条回答

我会这样做:

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

当可以map()在所有行上运行循环时,不要使用循环。你知道吗

def prefixWWW(url):
    return 'www.' + url if not url.startswith('www.') else url

df = df['url'].map(prefixWWW)

相关问题 更多 >