Suppose in a DataFrame we have a column 'Price', which contains missing values. What will be the proper code to fill the missing values with mean of the 'Price' column?
Suppose in a DataFrame we have a column 'Price', which contains missing values. What will be the proper code to fill the missing values with mean of the 'Price' column?
Solution
df['Price'].fillna(df['Price'].mean()) selects only the 'Price' column, calculates its mean (which skips NaN values by default), and fills the missing entries in that column with it.
It returns a new filled Series. To keep the change in the DataFrame, assign it back: df['Price'] = df['Price'].fillna(df['Price'].mean()).
Option 1: fillna is called on the whole DataFrame, so every column's missing values would be filled with the mean of 'Price', not just the 'Price' column.
Option 2: df['Price'] is used as an index inside df[...], which tries to select columns named by the price values and raises a KeyError.
Option 4: df.['Price'] is a syntax error, and even if corrected it would overwrite the entire column with the mean instead of filling only the missing values.
Related questions:
2025: 21 May Shift 1
2026: 24 May Shift 1
2026: 29 May Shift 2
2026: 20 May Shift 1
2025: 16 May Shift 1