def conditional_impute(input_df, choice='median') code example

Example 1: def conditional_impute(input_df, choice='median')

def conditional_impute(input_df, choice='median'):
    new_df = input_df.copy()
    
    if choice == 'median':
        new_df['Age'] = round(new_df.groupby(['Sex', 'Pclass'])['Age'].transform(func = lambda x: x.fillna(x.median())),1)
        
    elif choice == 'mean':
        new_df['Age'] = round(new_df.groupby(['Sex', 'Pclass'])['Age'].transform(func = lambda x: x.fillna(x.mean())),1)
        
    else:
        raise ValueError('Please choose either median or mean as your impute choice.')
    
    return new_df

Example 2: def conditional_impute(input_df, choice='median')

if choice == 'median':
        new_df['Age'] = new_df.groupby(['Sex', 'Pclass'])['Age'].transform(func = lambda x: x.fillna(round(x.median(),1)))