Fill Missing Column Values (fillna With Mean & Default)

Basics
BasicsPandasMissing ValuesMetaAmazonUber

Problem

Implement clean_missing(df) returning a copy of df where missing (NaN) values in score are filled with the mean of non-null score values, and missing values in city are filled with 'Unknown'.

Why It Matters: Column-specific imputation (numeric mean + categorical sentinel) is one of the first preprocessing steps before training ML models.

Function Signature

import pandas as pd

def clean_missing(df: pd.DataFrame) -> pd.DataFrame:

Sample Input & Output

Example 1: Mixed Numeric & String NaNs

Input:

scorecity
10.0NYC
NaNNaN
20.0LA

Expected Output:

scorecity
10.0NYC
15.0Unknown
20.0LA

Explanation: Mean of [10.0, 20.0] is 15.0, filling row 1's score; row 1's missing city becomes 'Unknown'.

Example 2: No Missing Values

Input:

scorecity
5.0SF
7.0Boston

Expected Output:

scorecity
5.0SF
7.0Boston

Explanation: Rows without NaNs remain completely unchanged.

Constraints & Edge Cases

  • Return a cleaned copy of df.
  • Do not mutate the input DataFrame (out = df.copy()).
  • Compute out['score'].mean() ignoring NaNs (Pandas default).

Constraints & Evaluation Criteria

  • Return a cleaned copy of `df`.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
score=[10, nan, 20], city=['NYC', None, 'LA']
Expected Output / Criteria
score=[10,15,20], city=['NYC','Unknown','LA']