【问题标题】:Trying to apply a function on a Pandas DataFrame in Python尝试在 Python 中的 Pandas DataFrame 上应用函数
【发布时间】:2020-06-18 00:49:07
【问题描述】:

我正在尝试应用此函数来填充基于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:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您应该考虑使用括号来分隔参数(您已经这样做了)并将布尔运算符 and 更改为按位运算符 & 以避免此类错误。另外,请记住,如果您想使用 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 
    

    现在,将 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
    

    【讨论】:

    • 感谢您的意见。即使将and 替换为&,我也得到了完全相同的结果
    猜你喜欢
    • 2017-11-14
    • 2021-10-14
    • 1970-01-01
    • 2017-09-06
    • 2017-10-14
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2019-07-01
    相关资源
    最近更新 更多