在条件下用最频繁的数字替换缺失值

问题描述

我正在尝试替换“年龄”列的缺失值,但在此数据的其他列的情况下Titanic - Machine Learning from Disaster

df.Age[(df['Sex'] == 0) & (df['Pclass'] == 1)]

我尝试使用 SimpleImputer 做到这一点:

from sklearn.impute import SimpleImputer
Imputer = SimpleImputer(missing_values=np.nan,strategy='most_frequent')

Imputer.fit_transform( pd.DataFrame(df.Age[(df['Sex'] == 0) & (df['Pclass'] == 1)]) )

但它不起作用并试图将值保存到列中:

df.loc[(df.Age.isnull()) & (df.Age[(df['Sex'] == 0) & (df['Pclass'] == 1)]),'Age'] = Imputer.fit_transform( pd.DataFrame(df.Age[(df['Sex'] == 0) & (df['Pclass'] == 1)]) )

但也不起作用。

我尝试使用 fillna()

手动执行此操作
df.loc[(df['Sex'] == 0) & (df['Pclass'] == 1),'Age'].fillna(int(df.Age[(df['Sex'] == 0) & (df['Pclass'] == 1)].mode()),inplace=True)

我尝试使用索引来访问行并更新它们的值:

mod = int(df.Age[(df['Sex'] == 0) & (df['Pclass'] == 1)].mode())
indices = df.loc[(df.Age.isnull()) & (df.Sex == 0) & (df.Pclass == 1),'Age'].isnull().index
df.loc[ind,'Age'] = mod
df[(df['Sex'] == 0) & (df['Pclass'] == 1)]['Age'].isnull().sum()

它有效并且输出为:0,但是当我尝试将它应用于 for 循环时,它给了我一个错误

for i in range(1,3):
    for j in range(1,4):    
        indices = df.loc[(df.Sex == i) & (df.Pclass == j),'Age'].isnull().index
        mod = int(df.Age[(df['Sex'] == i) & (df['Pclass'] == j)].mode())
        df.loc[ind,'Age'] = mod

我想知道前两种方式有什么问题,为什么第三种不能循环工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)