如何使用Python检查函数参数是否存在?

2024-04-19 00:29:56 发布

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

我的代码是:

def load_data(datafile, categories=None, cat_columns=None):
    ohe_categories = 'auto'
    if categories and len(categories) > 0:
        ohe_categories = categories
    ohe = OneHotEncoder(handle_unknown='ignore', categories=ohe_categories)

categoriesNone时,它工作正常。但是如果我传递了什么,我会得到一个错误:

ValueError: The truth value of a Index is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

调用函数时使用:

training_x, training_y, categories, cat_columns = loader.load_data(
    'data/training.csv')

test_x, test_y = loader.load_data(
    'data/test.csv', categories=categories, cat_columns=cat_columns)

如何正确检查?你知道吗


Tags: columnscsv代码testnoneautodatadef
2条回答

我建议:

def load_data(datafile, categories=None, cat_columns=None):
    ohe_categories = 'auto'
    if categories is not None:
        if len(categories) > 0:
            ohe_categories = categories
    ohe = OneHotEncoder(handle_unknown='ignore', categories=ohe_categories)

您正在传递一个不支持转换为bool的值。在这种情况下,需要显式检查值是否不是None

if categories is not None:

相关问题 更多 >