📖 Scenario: Imagine you have a small table of daily temperatures, but some days are missing values. You want to fill in those missing days by using the last known temperature or the next known temperature.
🎯 Goal: You will create a pandas DataFrame with some missing temperature values. Then, you will add variables to control filling methods. Next, you will apply forward fill and backward fill to fill missing values. Finally, you will print the filled DataFrames.
📋 What You'll Learn
Create a pandas DataFrame called temps with dates as index and temperature values including NaN
Create a variable called fill_method to choose between forward fill and backward fill
Use the fillna() method with method=fill_method to fill missing values
Print the filled DataFrame
💡 Why This Matters
🌍 Real World
Data often has missing values. Filling missing data helps keep analysis accurate and complete, like filling missing temperature readings in weather data.
💼 Career
Data scientists and analysts frequently clean data by filling missing values to prepare datasets for modeling and reporting.
Progress0 / 4 steps
1
Create the temperature DataFrame with missing values
Import pandas as pd. Create a DataFrame called temps with the dates '2024-06-01' to '2024-06-05' as the index. The temperature values should be 20.5, NaN, 22.0, NaN, and 23.5 respectively.
Pandas
Hint
Use pd.date_range to create the dates index. Use np.nan for missing values.
2
Create a variable to select fill method
Create a variable called fill_method and set it to the string 'ffill' to represent forward fill.
Pandas
Hint
Set fill_method exactly to the string 'ffill'.
3
Apply forward fill or backward fill to fill missing values
Create a new DataFrame called filled_temps by applying temps.fillna(method=fill_method) to fill missing values using the method stored in fill_method.
Pandas
Hint
Use the fillna() method with the method parameter set to fill_method.
4
Print the filled DataFrame
Print the filled_temps DataFrame to see the result of forward fill.
Pandas
Hint
Use print(filled_temps) to show the DataFrame.
Practice
(1/5)
1. What does the forward fill method do in pandas when handling missing data?
easy
A. It copies the next known value backward to fill missing spots.
B. It copies the last known value forward to fill missing spots.
C. It replaces missing values with zero.
D. It removes rows with missing values.
Solution
Step 1: Understand forward fill concept
Forward fill means filling missing data by copying the last valid value forward.
Step 2: Compare options with definition
It copies the last known value forward to fill missing spots. matches this exactly, while others describe different methods.
Final Answer:
It copies the last known value forward to fill missing spots. -> Option B
Quick Check:
Forward fill = copy last known value forward [OK]
Hint: Forward fill copies previous value downwards [OK]
Common Mistakes:
Confusing forward fill with backward fill
Thinking forward fill removes missing data
Assuming forward fill replaces with zero
2. Which of the following is the correct pandas syntax to perform a backward fill on a DataFrame df?
easy
A. df.fillna(method='backfill')
B. df.fillna(method='ffill')
C. df.fillna(backward=True)
D. df.fillna(direction='backward')
Solution
Step 1: Recall pandas fillna syntax
Backward fill uses method='backfill' or method='bfill' in fillna.
Step 2: Check options for correct syntax
df.fillna(method='backfill') uses method='backfill', which is correct. Others are invalid or incorrect syntax.
Final Answer:
df.fillna(method='backfill') -> Option A
Quick Check:
Backward fill syntax = method='backfill' [OK]
Hint: Use method='backfill' for backward fill in fillna [OK]
After running this, what is the content of column 'B' in df?
medium
A. [2, 2, 4, 4]
B. [None, 2, None, 4]
C. [2, 2, 2, 4]
D. [None, 2, 4, 4]
Solution
Step 1: Understand backward fill with inplace=True
Backward fill copies next valid value upwards, modifying df directly.
Step 2: Apply backward fill to column 'B'
Index 0: None filled with next valid 2 Index 1: 2 (valid) Index 2: None filled with next valid 4 Index 3: 4 (valid)
Final Answer:
[2, 2, 4, 4] -> Option A
Quick Check:
Backward fill copies next valid value up [OK]
Hint: Backward fill copies next valid value upward [OK]
Common Mistakes:
Not using inplace=True and expecting df to change
Confusing backward fill with forward fill
Leaving None values unchanged
5. You have a DataFrame df with missing values scattered in multiple columns. You want to fill missing values by first forward filling, then backward filling any remaining missing values. Which code snippet correctly achieves this?
hard
A. df.fillna(method='ffill', method='bfill')
B. df.fillna(method='bfill').fillna(method='ffill')
C. df.fillna(method='ffill').fillna(method='bfill')
D. df.fillna(method=['ffill', 'bfill'])
Solution
Step 1: Understand chaining fillna methods
First forward fill fills missing values from previous valid data, then backward fill fills remaining missing values from next valid data.
Step 2: Analyze options for correct chaining
df.fillna(method='ffill').fillna(method='bfill') chains fillna with method='ffill' then method='bfill', which is correct. df.fillna(method='bfill').fillna(method='ffill') reverses order, which may fill differently. Options C and D use invalid syntax.
Final Answer:
df.fillna(method='ffill').fillna(method='bfill') -> Option C
Quick Check:
Chain forward then backward fill to cover all missing [OK]
Hint: Chain fillna with ffill then bfill to fill all gaps [OK]
Common Mistakes:
Using invalid syntax with multiple methods in one fillna
Reversing order and missing some fills
Expecting one fillna call to do both fills
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.