首页 > 解决方案 > 尝试在 Python 中的 Pandas DataFrame 上应用函数

问题描述

我正在尝试应用此函数来填充Age基于Pclass和列的Sex列。但我无法这样做。我怎样才能让它工作?

def fill_age():
    Age = train['Age']
    Pclass = train['Pclass']
    Sex = train['Sex']

    if pd.isnull(Age):
        if Pclass == 1:
            return 34.61
        elif (Pclass == 1) and (Sex == 'male'):
            return 41.2813 
        elif (Pclass == 2) and (Sex == 'female'):
            return 28.72
        elif (Pclass == 2) and (Sex == 'male'):
            return 30.74
        elif (Pclass == 3) and (Sex == 'female'):
            return 21.75 
        elif (Pclass == 3) and (Sex == 'male'):
            return 26.51 
        else:
            pass
    else:
        return Age 


train['Age'] = train['Age'].apply(fill_age(),axis=1)

我收到以下错误:

ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

标签: pythonpandas

解决方案


您应该考虑使用括号来分隔参数(您已经这样做了)并更改按位运算符的布尔运算符and&避免此类错误。另外,请记住,如果要使用apply,则应x为函数使用参数,该参数将成为函数中 lambda 的一部分apply

def fill_age(x):
    Age = x['Age']
    Pclass = x['Pclass']
    Sex = x['Sex']

    if pd.isnull(Age):
        if Pclass == 1:
            return 34.61
        elif (Pclass == 1) & (Sex == 'male'):
            return 41.2813 
        elif (Pclass == 2) & (Sex == 'female'):
            return 28.72
        elif (Pclass == 2) & (Sex == 'male'):
            return 30.74
        elif (Pclass == 3) & (Sex == 'female'):
            return 21.75 
        elif (Pclass == 3) & (Sex == 'male'):
            return 26.51 
        else:
            pass
    else:
        return Age 

现在,将 apply 与 lambda 一起使用:

train['Age'] = train['Age'].apply(lambda x: fill_age(x),axis=1)

在示例数据框中:

df = pd.DataFrame({'Age':[1,np.nan,3,np.nan,5,6],
                   'Pclass':[1,2,3,3,2,1],
                   'Sex':['male','female','male','female','male','female']})

使用上面提供的答案:

df['Age'] = df.apply(lambda x: fill_age(x),axis=1)

输出:

    Age  Pclass     Sex
0   1.00       1    male
1  28.72       2  female
2   3.00       3    male
3  21.75       3  female
4   5.00       2    male
5   6.00       1  female

推荐阅读