Skip to main content
 首页 » 编程设计

python之如何简化 IF 语句

2025年05月04日14artech

所以我在 python 中有一个 IF 语句,它本质上是将数据集中的空值更改为基于其他两列的平均值。

def impute_age(cols): 
    Age = cols[0] 
    Pclass = cols[1] 
    Sex = cols[2] 
 
    if pd.isnull(Age): 
        if Pclass == 1 and Sex == 0: 
            return train.loc[(train["Pclass"] == 1)  
                         & (train["Sex_male"] == 0)]["Age"].mean()  
        if Pclass == 2 and Sex == 0: 
            return train.loc[(train["Pclass"] == 2)  
                         & (train["Sex_male"] == 0)]["Age"].mean() 
        if Pclass == 3 and Sex == 0: 
            return train.loc[(train["Pclass"] == 3)  
                         & (train["Sex_male"] == 0)]["Age"].mean() 
        if Pclass == 1 and Sex == 1: 
            return train.loc[(train["Pclass"] == 1)  
                         & (train["Sex_male"] == 1)]["Age"].mean() 
        if Pclass == 2 and Sex == 1: 
            return train.loc[(train["Pclass"] == 2)  
                         & (train["Sex_male"] == 1)]["Age"].mean() 
        if Pclass == 3 and Sex == 1: 
            return train.loc[(train["Pclass"] == 3)  
                         & (train["Sex_male"] == 1)]["Age"].mean() 
    else: 
        return Age 

所以我在这里尝试使用某些乘客类别中男性/女性的平均年龄来填写 nans。我觉得会有更好的写法,尤其是当我遇到一个更大的数据集时。 作为引用,train df 是包含所有数据的主要 df。出于某种原因,我无法让这段代码与使用 cols 参数传递的火车子集一起工作。

这里的问题本质上是:我如何以更简单的方式编写此代码?如果我的数据集大得多,是否有一种方法可以编写此 IF 语句?

请您参考如下方法:

在我看来,您需要做的就是参数化您的内部if:

if pd.isnull(Age): 
    return train.loc[(train["Pclass"] == Pclass)  
                   & (train["Sex_male"] == Sex)]["Age"].mean()