Why data cleaning consumes most analysis time in Data Analysis Python - Performance Analysis
Data cleaning often takes the longest in data analysis. We want to understand why it costs so much time as data size grows.
How does the time needed to clean data change when we get more data?
Analyze the time complexity of the following code snippet.
import pandas as pd
def clean_data(df):
df = df.drop_duplicates()
df = df.fillna(method='ffill')
df['column'] = df['column'].apply(lambda x: x.strip() if isinstance(x, str) else x)
return df
This code removes duplicates, fills missing values, and cleans text in one column.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all rows multiple times for duplicates, missing values, and text cleaning.
- How many times: Each operation goes through the entire dataset once or more.
As the number of rows grows, each cleaning step takes longer because it checks every row.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 operations (3 passes over 10 rows) |
| 100 | About 300 operations (3 passes over 100 rows) |
| 1000 | About 3000 operations (3 passes over 1000 rows) |
Pattern observation: The time grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the cleaning time grows linearly with the amount of data.
[X] Wrong: "Data cleaning time stays the same no matter how much data there is."
[OK] Correct: Cleaning checks every row, so more data means more work and more time.
Understanding how data cleaning scales helps you explain why it takes so long and shows you can think about real data challenges clearly.
"What if we added nested loops to compare every row with every other row during cleaning? How would the time complexity change?"
Practice
Solution
Step 1: Understand real-world data quality
Real-world data is often messy with missing or wrong values.Step 2: Recognize cleaning tasks
Cleaning fixes these issues to prepare data for analysis.Final Answer:
Because real-world data often has missing or incorrect values that need fixing -> Option CQuick Check:
Messy data = cleaning time [OK]
- Thinking cleaning is about building models
- Confusing cleaning with visualization
- Assuming cleaning just deletes data
'age' with the mean age?Solution
Step 1: Identify correct method to fill missing values
Thefillna()method replaces missing values;inplace=Trueupdates the DataFrame directly.Step 2: Check correct usage of mean for replacement
df['age'].mean()calculates the mean of the 'age' column correctly.Final Answer:
df['age'].fillna(df['age'].mean(), inplace=True) -> Option DQuick Check:
fillna with mean = correct syntax [OK]
- Using replace with string 'NaN' instead of np.nan
- Wrong method fillna arguments
- Dropping missing values instead of filling
import pandas as pd
df = pd.DataFrame({'score': [10, None, 20, None, 30]})
df['score'] = df['score'].fillna(int(df['score'].median()))
print(df['score'].tolist())What is the output list?
Solution
Step 1: Calculate median of non-missing scores
Non-missing values are [10, 20, 30]. Median is 20.Step 2: Replace null with median
Missing values replaced by 20, so list becomes [10, 20, 20, 20, 30].Final Answer:
[10, 20, 20, 20, 30] -> Option AQuick Check:
Median fill replaces null with 20 [OK]
- Using mean instead of median
- Not replacing null values
- Confusing null with string 'null'
df.drop_duplicates() print(len(df))
What is the main issue?
Solution
Step 1: Understand drop_duplicates behavior
By default, drop_duplicates() returns a new DataFrame and does not change original unless inplace=True or reassigned.Step 2: Check code effect on original DataFrame
Since result is not saved or inplace=True used, original df remains unchanged, so length stays same.Final Answer:
drop_duplicates() does not remove duplicates without inplace=True or reassignment -> Option AQuick Check:
Use inplace=True or assign result [OK]
- Assuming drop_duplicates changes df without inplace
- Thinking len(df) excludes duplicates automatically
- Believing drop_duplicates needs column argument always
['name', 'age', 'income']. Some age values are missing, and some income values are negative due to data entry errors. Which sequence of cleaning steps is best to prepare data for analysis?Solution
Step 1: Handle missing 'age' values
Filling missing 'age' with median preserves data without bias from zeros or deletion.Step 2: Fix negative 'income' errors
Replacing negative 'income' with zero corrects errors without deleting data.Final Answer:
Fill missing 'age' with median, then replace negative 'income' with zero -> Option BQuick Check:
Median fill + zero fix = best cleaning [OK]
- Deleting rows unnecessarily
- Filling missing with zero causing bias
- Replacing errors with mean without fixing negatives
Ready to prove it?
Pass the test and this pattern moves unknown
