python - 如何将 'www.' 添加到某些数据帧值的开头?

标签 python string pandas iteration

我有包含域名的数据:

 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)

关于python - 如何将 'www.' 添加到某些数据帧值的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42753385/

相关文章:

python - String.maketrans 用于英语和波斯语数字

python - `@numba.jitclass` ed 特殊方法去哪里了?

python - 为什么我的输入错误陷阱不能按我预期的方式工作?

java - 创建数组的区别

python - 如何修复 str 的重新定义?

python - 如何根据另一个 DataFrame 的条件从多索引 Dataframe 中选择重复子集

python - Pandas 读取 json 不适用于 MultiIndex

python - 为什么我在 Python 中遇到溢出错误?

ruby - 为什么我不能用 gsub 替换字符串中的 '\\+'?

python - 想要比较两列中的字符串并在 python pandas 中的同一行中引入相等的值