【问题标题】:Filling missing age in titanic dataset填补泰坦尼克数据集中缺失的年龄
【发布时间】:2020-04-20 04:17:07
【问题描述】:

我知道这有数百种解决方案,但我想知道是否有更聪明的方法来填充熊猫的数据框,它根据以下冗长的某些条件来填充缺少年龄列。

mean_value = df[(df["Survived"]== 1) & (df["Pclass"] == 1) & (df["Sex"] == "male")
                & (df["Embarked"] == "C") & (df["SibSp"] == 0) & (df["Parch"] == 0)].Age.mean().round(2)

df = df.assign(
    Age=np.where(df.Survived.eq(1) & df.Pclass.eq(1) & df.Sex.eq("male") & df.Embarked.eq("C") &
                 df.SibSp.eq(0) & df.Parch.eq(0) & df.Age.isnull(), mean_value, df.Age)
)

对以上所有 6 列重复以下内容,所有分类组合都太长太笨重,我想知道是否有更聪明的方法来做到这一点?

@Ben.T 回答:

如果我正确理解了你的方法,这是它的“详细版本”吗?

for a in np.unique(df.Survived):
    for b in np.unique(df.Pclass):
        for c in np.unique(df.Sex):
            for d in np.unique(df.SibSp):
                for e in np.unique(df.Parch):
                    for f in np.unique(df.Embarked):
                        mean_value = df[(df["Survived"] == a) & (df["Pclass"] == b) & (df["Sex"] == c)
                                        & (df["SibSp"] == d) & (df["Parch"] == e) & (df["Embarked"] == f)].Age.mean()

                        df = df.assign(Age=np.where(df.Survived.eq(a) & df.Pclass.eq(b) & df.Sex.eq(c) & df.SibSp.eq(d) &
                                                    df.Parch.eq(e) & df.Embarked.eq(f) & df.Age.isnull(), mean_value, df.Age))

哪个等价于这个?

l_col = ['Survived','Pclass','Sex','Embarked','SibSp','Parch']
df['Age'] = df['Age'].fillna(df.groupby(l_col)['Age'].transform('mean'))

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以创建一个组合所有条件的变量,然后您可以使用 & 号稍后添加更多条件。

    注意,在我从中获取数据的 seaborn titanic 数据集中,列名是小写的。

    criteria = ((df["survived"]== 1) & 
                (df["pclass"] == 1) & 
                (df["sex"] == "male") & 
                (df["embarked"] == "C") & 
                (df["sibsp"] == 0) & 
                (df["parch"] == 0))
    
    fillin = df.loc[criteria, 'age'].mean()
    
    df.loc[criteria & (df['age'].isnull()), 'age'] = fillin
    

    【讨论】:

    • 感谢@Eric 的回答,但这还不是很长,因为我必须对所有标准进行硬编码?
    【解决方案2】:

    我猜groupby.transform 可以做到。它在groupby 中的所有列组上为每一行创建mean,并同时为所有可能的组合执行此操作。然后将fillna 与创建的系列一起使用将使用具有相同特征的组的mean 填充缺失值。

    l_col = ['Survived','Pclass','Sex','Embarked','SibSp','Parch']
    df['Age'] = df['Age'].fillna(df.groupby(l_col)['Age'].transform('mean'))
    

    【讨论】:

    • 我在问题上添加了一些更新以反映我的评论,因为评论区太短了。不知道为什么会有不同的缺失值。也许我误解了这一点。
    • @JosephAdam 是的,您的详细信息似乎与 groupby 方法相同。但是对于差异,我不能肯定地说,因为我没有数据。
    • 谢谢!我刚刚想通了。这是我这边的错误数据输入。你的方法超级干净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2021-07-29
    • 2022-07-25
    • 2017-06-27
    • 2020-10-25
    • 2016-06-19
    • 2022-01-03
    相关资源
    最近更新 更多