Why systematic cleaning matters in Pandas - Performance Analysis
We want to see how the time it takes to clean data grows as the data gets bigger.
How does cleaning many rows affect how long the process takes?
Analyze the time complexity of the following code snippet.
import pandas as pd
def clean_data(df):
df = df.dropna()
df['age'] = df['age'].astype(int)
df = df[df['salary'] > 0]
df['name'] = df['name'].str.strip()
return df
# Example usage:
# cleaned_df = clean_data(raw_df)
This code removes missing data, converts ages to integers, filters positive salaries, and trims spaces from names.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Going through each row to check for missing values, convert types, filter, and trim strings.
- How many times: Each operation touches all rows once, so roughly once per row per step.
As the number of rows grows, the time to clean grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 40 (4 steps x 10 rows) |
| 100 | About 400 (4 steps x 100 rows) |
| 1000 | About 4000 (4 steps x 1000 rows) |
Pattern observation: Doubling the rows roughly doubles the work needed.
Time Complexity: O(n)
This means the cleaning time grows linearly with the number of rows in the data.
[X] Wrong: "Cleaning a few columns is always very fast, no matter how many rows there are."
[OK] Correct: Even if you clean only a few columns, every row still needs to be checked, so time grows with the number of rows.
Understanding how cleaning scales helps you explain your approach clearly and shows you think about efficiency in real data tasks.
"What if we added a nested loop to clean data by comparing each row to every other row? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of cleaning data
Cleaning removes errors and inconsistencies that can mislead analysis.Step 2: Connect cleaning to analysis trustworthiness
Systematic cleaning ensures results are based on correct and consistent data.Final Answer:
It helps ensure the analysis results are accurate and reliable. -> Option CQuick Check:
Cleaning = Accurate results [OK]
- Thinking cleaning only changes data appearance
- Believing cleaning adds new data automatically
- Assuming cleaning increases data size
Solution
Step 1: Identify function to remove missing data
df.dropna() removes rows with any missing (NaN) values.Step 2: Differentiate from other functions
df.fillna() fills missing values, drop_duplicates() removes duplicate rows, replace() changes values.Final Answer:
df.dropna() -> Option BQuick Check:
Remove missing rows = dropna() [OK]
- Confusing fillna() with dropna()
- Using drop_duplicates() to remove missing values
- Trying replace() to drop rows
import pandas as pd
data = {'Name': ['Anna', 'Bob', None, 'Diana'], 'Age': [25, None, 30, 22]}
df = pd.DataFrame(data)
df_clean = df.dropna()
print(df_clean)Solution
Step 1: Understand dropna() behavior
dropna() removes rows with any missing (None/NaN) values in any column.Step 2: Apply dropna() to given data
Rows with None in 'Name' or 'Age' are removed, leaving only rows with complete data.Final Answer:
DataFrame with only rows where 'Name' and 'Age' are not None -> Option AQuick Check:
dropna() removes rows with missing values [OK]
- Expecting dropna() to fill missing values
- Thinking dropna() removes columns instead of rows
- Assuming dropna() causes an error without parameters
import pandas as pd
data = {'A': [1, 2, 2, 3], 'B': [4, 5, 5, 6]}
df = pd.DataFrame(data)
df.drop_duplicates()
print(df)Solution
Step 1: Check drop_duplicates() usage
By default, drop_duplicates() returns a new DataFrame and does not change the original unless inplace=True or reassigned.Step 2: Identify why duplicates remain
Since df.drop_duplicates() is called without assignment or inplace=True, df remains unchanged.Final Answer:
drop_duplicates() does not remove duplicates without inplace=True or reassignment. -> Option DQuick Check:
drop_duplicates() needs inplace or assignment [OK]
- Assuming drop_duplicates() modifies original DataFrame by default
- Thinking drop_duplicates() needs column argument always
- Believing drop_duplicates() cannot work on numbers
Solution
Step 1: Remove extra spaces
str.strip() removes leading and trailing spaces effectively.Step 2: Fix capitalization
str.title() converts text to title case, making capitalization consistent.Step 3: Avoid unnecessary replacements
Removing all spaces or replacing spaces incorrectly can harm data integrity.Final Answer:
df['City'] = df['City'].str.strip().str.title() -> Option AQuick Check:
Strip spaces + title case = clean text [OK]
- Removing all spaces inside city names
- Applying inconsistent capitalization methods
- Overcomplicating cleaning with unnecessary replacements
Ready to prove it?
Pass the test and this pattern moves unknown
