What if you could fix all missing data in your table with just one simple command?
Why Filling missing values with fillna() in Pandas? - Purpose & Use Cases
Imagine you have a big table of data about your friends' favorite movies, but some spots are empty because they forgot to tell you. You want to fill those empty spots so you can understand the list better.
Trying to fill those empty spots by hand is slow and easy to mess up. You might miss some, fill wrong values, or spend hours checking each spot. This makes your work frustrating and full of mistakes.
The fillna() function in pandas quickly fills all empty spots with a value you choose or a smart guess. It saves time, avoids errors, and makes your data ready for analysis in seconds.
for i in range(len(data)): if pd.isna(data['movie'][i]): data['movie'][i] = 'Unknown'
data['movie'] = data['movie'].fillna('Unknown')
With fillna(), you can clean messy data fast and focus on finding cool patterns or answers.
A teacher has a spreadsheet of student test scores but some scores are missing. Using fillna(), the teacher fills missing scores with the class average to fairly compare all students.
Manually filling missing data is slow and error-prone.
fillna() fills missing values quickly and correctly.
This helps prepare data for better analysis and decisions.
Practice
fillna() function do in pandas?Solution
Step 1: Understand the purpose of fillna()
Thefillna()function is designed to handle missing data by replacing NaN values with a specified value or method.Step 2: Compare options with fillna() behavior
Options B, C, and D describe other DataFrame operations, but only It replaces missing values with specified values. correctly describes filling missing values.Final Answer:
It replaces missing values with specified values. -> Option DQuick Check:
fillna() = replace missing values [OK]
- Confusing fillna() with dropna() which removes rows
- Thinking fillna() sorts data
- Assuming fillna() changes data types
df with zero using fillna()?Solution
Step 1: Recall fillna() method syntax
The correct way to fill missing values is callingfillna()with the value as the first argument, likedf.fillna(0).Step 2: Evaluate each option
df.fillna = 0 tries to assign to fillna which is incorrect. df.fillna(na=0) uses a wrong keyword argument. df.fillna(0, value=0) passes 0 both positionally (as value) and explicitly as value=0 keyword, causing TypeError: multiple values for argument 'value'. Only C is correct.Final Answer:
df.fillna(0) -> Option CQuick Check:
fillna(value) fills missing with value [OK]
- Assigning fillna instead of calling it as a method
- Using wrong argument names like na=0
- Confusing inplace parameter usage
import pandas as pd
df = pd.DataFrame({'A': [1, None, 3], 'B': [None, 2, None]})
filled = df.fillna({'A': 0, 'B': 5})
print(filled)What is the output?
Solution
Step 1: Understand fillna() with dict argument
Using a dictionary with fillna() fills missing values in each column with the corresponding value from the dict. Here, column 'A' missing values become 0, and column 'B' missing values become 5.Step 2: Apply fillna() to each column
Original df has NaN at df.loc[1, 'A'] and df.loc[0, 'B'], df.loc[2, 'B']. After fillna, these become 0 for 'A' and 5 for 'B'. The rest of the values remain unchanged.Final Answer:
A B 0 1 5 1 0 2 2 3 5 -> Option AQuick Check:
fillna(dict) fills columns separately [OK]
- Expecting fillna() to fill all columns with same value
- Confusing NaN replacement with zero by default
- Misreading which values are replaced
import pandas as pd
df = pd.DataFrame({'X': [None, 2, None]})
df.fillna(inplace=True, 0)
print(df)Solution
Step 1: Check fillna() parameter names and order
In Python functions, all positional arguments must come before any keyword arguments.Step 2: Identify incorrect argument order
The code usesinplace=True(keyword) followed by0(positional for value), which raises SyntaxError: positional argument follows keyword argument. Correct isdf.fillna(0, inplace=True).Final Answer:
The arguments to fillna() are in wrong order. -> Option BQuick Check:
Positional args before keywords [OK]
- Swapping argument order without keywords
- Using inplace without value argument
- Confusing positional and keyword arguments
df with columns 'Score' and 'Grade'. 'Score' has missing values. You want to fill missing 'Score' values with the mean of 'Score' and then fill missing 'Grade' values with 'Unknown'. Which code correctly does this?Solution
Step 1: Calculate mean and prepare fill dictionary
We calculate the mean of 'Score' usingdf['Score'].mean()and want to fill missing 'Score' with this mean. For 'Grade', missing values should be filled with 'Unknown'.Step 2: Use fillna() with a dictionary and inplace=True
Usingdf.fillna({'Score': mean_value, 'Grade': 'Unknown'}, inplace=True)fills missing values in both columns correctly in one step.Step 3: Evaluate other options
df['Score'].fillna(df['Score'].mean()) df['Grade'].fillna('Unknown') does not assign back the filled columns, so missing values remain. df.fillna({'Score': 'Unknown', 'Grade': df['Grade'].mean()}, inplace=True) swaps fill values incorrectly. df.fillna(df.mean(), inplace=True) df['Grade'].fillna('Unknown') fills 'Score' with its column mean (assuming 'Score' numeric) but the second line returns a new Series without assignment or inplace=True, leaving 'Grade' unchanged.Final Answer:
df.fillna({'Score': df['Score'].mean(), 'Grade': 'Unknown'}, inplace=True) -> Option AQuick Check:
Use dict with fillna() and inplace=True for multiple columns [OK]
- Not assigning back after fillna() without inplace
- Mixing fill values between columns
- Using fillna() separately without inplace or assignment
Ready to prove it?
Pass the test and this pattern moves unknown
