Forward fill and backward fill in Pandas - Time & Space Complexity
We want to understand how the time it takes to fill missing data grows as the data size increases.
Specifically, how does forward fill or backward fill behave when applied to larger data?
Analyze the time complexity of the following code snippet.
import pandas as pd
import numpy as np
# Create a DataFrame with missing values
n = 1000
data = pd.DataFrame({
'A': np.random.choice([1, np.nan], size=n)
})
# Forward fill missing values
filled = data.ffill()
# Backward fill missing values
filled_back = data.bfill()
This code creates a column with some missing values and fills them forward and backward.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the column values once to fill missing data.
- How many times: Each element is visited once in order for forward fill, and once for backward fill.
As the number of rows increases, the time to fill missing values grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to fill |
| 100 | About 100 steps to fill |
| 1000 | About 1000 steps to fill |
Pattern observation: The work grows linearly as the data size grows.
Time Complexity: O(n)
This means the time to fill missing values grows directly with the number of rows.
[X] Wrong: "Forward fill checks every previous value multiple times, so it takes much longer than linear time."
[OK] Correct: The fill methods scan the data only once in order, so each element is visited once, making it linear time.
Understanding how filling missing data scales helps you handle larger datasets efficiently and shows you know how pandas works under the hood.
What if we applied forward fill on multiple columns at once? How would the time complexity change?
Practice
forward fill method do in pandas when handling missing data?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 BQuick Check:
Forward fill = copy last known value forward [OK]
- Confusing forward fill with backward fill
- Thinking forward fill removes missing data
- Assuming forward fill replaces with zero
df?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 AQuick Check:
Backward fill syntax = method='backfill' [OK]
- Using method='ffill' for backward fill
- Passing invalid parameters like backward=True
- Confusing method names in fillna
import pandas as pd
df = pd.DataFrame({'A': [1, None, None, 4, None]})
df_filled = df.fillna(method='ffill')What is the content of
df_filled?Solution
Step 1: Understand forward fill on the DataFrame
Forward fill copies last valid value downwards to fill missing values.Step 2: Apply forward fill step-by-step
Index 0: 1 (valid)
Index 1: filled with 1
Index 2: filled with 1
Index 3: 4 (valid)
Index 4: filled with 4Final Answer:
[1, 1, 1, 4, 4] -> Option DQuick Check:
Forward fill propagates last valid value forward [OK]
- Thinking forward fill leaves trailing NAs unfilled
- Failing to propagate through consecutive NAs
- Confusing forward fill with backward fill
import pandas as pd
df = pd.DataFrame({'B': [None, 2, None, 4]})
df.fillna(method='bfill', inplace=True)After running this, what is the content of column 'B' in
df?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 AQuick Check:
Backward fill copies next valid value up [OK]
- Not using inplace=True and expecting df to change
- Confusing backward fill with forward fill
- Leaving None values unchanged
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?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 CQuick Check:
Chain forward then backward fill to cover all missing [OK]
- Using invalid syntax with multiple methods in one fillna
- Reversing order and missing some fills
- Expecting one fillna call to do both fills
Ready to prove it?
Pass the test and this pattern moves unknown
