Skip to main contentSkip to solution

Given the following Python Statement:

df = pd.DataFrame({'A': [1, 2, np.nan], 'B': [5, np.nan, 6]})

Which of the following query will fill the missing values with the mean of that column?

Solution

✅ Correct Option: 3

df.mean() returns a Series with the mean of each column, skipping NaN. Here that is A = 1.5 and B = 5.5. When fillna() receives a Series, it matches its index to the column names and fills the NaNs in each column with that column's mean.

A: 1+22=1.5,B: 5+62=5.5\text{A: } \dfrac{1+2}{2} = 1.5, \quad \text{B: } \dfrac{5+6}{2} = 5.5

So df.fillna(df.mean()) gives A = [1, 2, 1.5] and B = [5, 5.5, 6].


Option 1: isna() only detects missing values, returning True/False, and takes no argument to fill with.

Option 2: df.fillna is a method, so indexing it with [...] is invalid syntax for filling.

Option 4: method='ffill' copies the previous value forward, not the column mean. It would also leave the first-row NaN unfilled if there were one.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question