python - 属性错误: 'module' object has no attribute 'ValueError'

标签 python pandas dataframe apply

所以我在使用 tld 库时遇到了错误,它不知道如何处理某些代理请求 URL。为了解决这个问题,添加了一些异常(exception)情况,并且它适用于特定日期的数据。

import tld
from tld import get_fld

#Custom try-except function to handle IPs and garbage http requests
def try_get_fld(x):
    try: 
        return get_fld(x)
    except tld.exceptions.TldBadUrl: 
        return np.nan
    except tld.exceptions.TldDomainNotFound:
        return np.nan

#Apply the function above to the request dataframe
request['flds'] = request['request'].apply(try_get_fld)

但是在另一天我遇到了一个新错误:

ValueError: Invalid IPv6 URL

所以我添加了异常(exception):

def try_get_fld(x):
    try: 
        return get_fld(x)
    except tld.exceptions.TldBadUrl: 
        return np.nan
    except tld.exceptions.TldDomainNotFound:
        return np.nan
    except tld.exceptions.ValueError:
        return np.nan

然后我遇到了属性错误:

AttributeError: 'module' object has no attribute 'ValueError'

所以我将其添加到异常(exception)中:

def try_get_fld(x):
    try: 
        return get_fld(x)
    except tld.exceptions.TldBadUrl: 
        return np.nan
    except tld.exceptions.TldDomainNotFound:
        return np.nan
    except tld.exceptions.ValueError:
        return np.nan
    except tld.exceptions.AttributeError:
        return np.nan

然后我再次收到 AttributeError: 'module' object has no attribute 'ValueError'。

有人知道我做错了什么或如何解决我的问题吗?目标只是用 NaN 标记请求 URL,以便我可以将该方法应用于我的数据集。

最佳答案

您可以指定异常列表,使您的代码简洁。

def try_get_fld(x):
    try: 
        return get_fld(x)
    except (tld.exceptions.TldBadUrl, 
            tld.exceptions.TldDomainNotFound, 
            ValueError): 
        return np.nan

关于python - 属性错误: 'module' object has no attribute 'ValueError' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53639958/

相关文章:

python - 仅替换 DataFrame 中最后一次出现的列值

r - 如何在R中的数据框中的列中查找和删除具有相同连续值的一定数量的行?

python - argparse 没有正确处理子解析器中的缩写

python - AWS boto3 源代码

python - 在函数内调用 return 时如何中断 Python Flask Controller 流程?

r - 使用 diff 函数和 mutate at from dplyr

python - 如何正确调用函数并返回更新的数据框?

python - 预期是二维数组,却得到了一维数组。如何解决这个问题?

python - 动态地将新字符串附加到现有字符串

python - 使用 Python pandas 检查列是否包含相同的值或 NaN