尝试在Python中的数据帧上应用函数

2024-10-01 22:42:47 发布

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

我试图应用这个函数来填充基于PclassSex列的Age列。但我不能这么做。我怎样才能让它工作

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: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().


Tags: and函数agereturnifdeftrainfill
1条回答
网友
1楼 · 发布于 2024-10-01 22:42:47

你应该考虑使用括号来分离参数(你已经做过了),并改变布尔运算符^ {< CD1>},以获得位类型opeActer ^ {CD2>},以避免这种类型的错误。此外,请记住,如果要使用apply,则应为函数使用参数x,该函数将成为apply函数中lambda的一部分:

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 

现在,对lambda使用apply:

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

相关问题 更多 >

    热门问题