Forward fill and backward fill in Data Analysis Python - Time & Space Complexity
We want to understand how the time to fill missing data grows as the data size increases.
How does the filling process scale when we have more data points?
Analyze the time complexity of the following code snippet.
import pandas as pd
df = pd.DataFrame({'A': [1, None, None, 4, None, 6]})
df_filled_forward = df.fillna(method='ffill')
df_filled_backward = df.fillna(method='bfill')
This code fills missing values in a column by carrying forward or backward the last known value.
- Primary operation: Scanning the data column once to fill missing values.
- How many times: Each element is visited once in forward fill and once in 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 forward and 10 steps backward |
| 100 | About 100 steps forward and 100 steps backward |
| 1000 | About 1000 steps forward and 1000 steps backward |
Pattern observation: The operations grow linearly with the number of data points.
Time Complexity: O(n)
This means the time to fill missing values grows in a straight line as data size grows.
[X] Wrong: "Forward fill or backward fill takes constant time regardless of data size."
[OK] Correct: Because each data point must be checked and possibly updated, the time grows with data size, not fixed.
Understanding how filling missing data scales helps you explain data cleaning steps clearly and shows you think about efficiency in real tasks.
"What if we filled missing values using a more complex method that looks at multiple columns? How would the time complexity change?"
Practice
forward fill do when handling missing data in a dataset?Solution
Step 1: Understand forward fill concept
Forward fill means filling missing data by copying the last known value forward to the next missing spot.Step 2: Compare options with definition
"It copies the last known value forward to fill missing spots." matches this definition exactly, while others describe different methods.Final Answer:
It copies the last known value forward to fill missing spots. -> Option DQuick 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
In pandas, forward fill is done byfillna(method='ffill').Step 2: Check options for correct syntax
df.fillna(method='ffill')matches the correct method name 'ffill'.df.fillna(method='bfill')performs backward fill. The remaining options use invalid syntax.Final Answer:
df.fillna(method='ffill') -> Option AQuick Check:
Forward fill method = 'ffill' [OK]
- Using 'bfill' instead of 'ffill' for forward fill
- Passing invalid parameters like forward=True
- Confusing method names in fillna
df below, what will be the result of df.bfill()?
import pandas as pd
df = pd.DataFrame({'A': [1, None, None, 4, None]})
print(df.bfill())Solution
Step 1: Understand backward fill on given data
Backward fill copies the next known value backward to fill missing spots. Here, missing values at index 1 and 2 get filled with 4.0 from index 3. The last missing at index 4 has no next value, so remains NaN.Step 2: Match output with options
A 0 1.0 1 4.0 2 4.0 3 4.0 4 NaN matches this result exactly. A 0 1.0 1 4.0 2 4.0 3 4.0 4 4.0 incorrectly fills last NaN with 4.0, others do not match.Final Answer:
A 0 1.0 1 4.0 2 4.0 3 4.0 4 NaN -> Option AQuick Check:
Backward fill fills missing with next known value [OK]
- Assuming last NaN gets filled when no next value exists
- Confusing forward and backward fill results
- Misreading index positions in output
import pandas as pd
df = pd.DataFrame({'A': [None, 2, None]})
df.fillna(method='forward')Solution
Step 1: Check fillna method parameter
The valid method names are 'ffill' for forward fill and 'bfill' for backward fill. 'forward' is not valid.Step 2: Identify cause of error
Using 'forward' causes a ValueError. DataFrames can have None values, fillna does not require inplace=True, and it accepts the method parameter.Final Answer:
The method name 'forward' is invalid; should be 'ffill'. -> Option CQuick Check:
Use 'ffill' for forward fill method [OK]
- Using 'forward' instead of 'ffill'
- Thinking inplace=True is mandatory
- Believing fillna can't handle None values
df with missing values scattered in column 'B'. You want to fill missing values by first forward filling, then backward filling any remaining missing values. Which code correctly does this?Solution
Step 1: Understand chaining fillna calls
To fill missing values first forward then backward, chain fillna calls: first with method='ffill', then on result with method='bfill'.Step 2: Evaluate options for correct chaining
df['B'].fillna(method='ffill').fillna(method='bfill') correctly chains fillna twice. df['B'].fillna(method='bfill').fillna(method='ffill') reverses order. Attempting multiple methods in one call (duplicate kwargs or list) uses invalid syntax.Final Answer:
df['B'].fillna(method='ffill').fillna(method='bfill') -> Option BQuick Check:
Chain fillna with 'ffill' then 'bfill' [OK]
- Trying to pass multiple methods in one fillna call
- Reversing forward and backward fill order
- Not chaining calls, so some NaNs remain
Ready to prove it?
Pass the test and this pattern moves unknown
