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?
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
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.
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.
Related questions:
2026: 29 May Shift 1
2026: 31 May Shift 1