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

Replace Missing Values with Most Frequent number under Condition

我正在尝试替换“年龄”列的缺失值,但在该数据的其他列的条件下 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

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

尝试使用方法垫。它采用最新的值。之后,您可以根据其他列的条件删除某些值。

df.fillna(method='pad')

这个解决方案很有效,但我不知道为什么上面的方法不起作用!

Imputer = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
for i in range(2):
    for j in range(1,4):
        ls = np.array(df.Age[((df.Sex==i) & (df.Pclass==j))]).reshape(-1,1)
        df.Age[((df.Sex==i) & (df.Pclass==j))] = Imputer.fit_transform(ls)[:,0]
df.Age.isnull().sum()