Removing duplicates (drop_duplicates) in Data Analysis Python - Time & Space Complexity
When we remove duplicates from data, we want to know how the time to do this changes as the data grows.
We ask: How much longer does it take if we have more rows?
Analyze the time complexity of the following code snippet.
import pandas as pd
data = pd.DataFrame({
'A': [1, 2, 2, 3, 4, 4, 4],
'B': ['x', 'y', 'y', 'z', 'x', 'x', 'x']
})
unique_data = data.drop_duplicates()
This code creates a table and removes rows that appear more than once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each row against others to find duplicates.
- How many times: Each row is hashed or checked once during the process.
As the number of rows grows, the work to find duplicates grows roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: Doubling the rows roughly doubles the work.
Time Complexity: O(n)
This means the time to remove duplicates grows directly with the number of rows.
[X] Wrong: "Removing duplicates takes much longer than just reading the data because it compares every row to every other row."
[OK] Correct: The method uses smart hashing or indexing to avoid checking every pair, so it does not compare all rows to all others.
Understanding how removing duplicates scales helps you explain data cleaning steps clearly and shows you know how data size affects processing time.
"What if we remove duplicates based on only one column instead of all columns? How would the time complexity change?"
Practice
drop_duplicates() function do in a pandas DataFrame?Solution
Step 1: Understand the function purpose
drop_duplicates()is used to remove repeated rows in a DataFrame.Step 2: Default behavior
By default, it checks all columns to find duplicates and keeps the first occurrence.Final Answer:
Removes repeated rows based on all columns by default -> Option BQuick Check:
drop_duplicates() removes repeated rows [OK]
- Thinking it sorts data
- Confusing with fillna()
- Assuming it changes data types
df?Solution
Step 1: Identify correct method call
The method to remove duplicates isdrop_duplicates(), called with parentheses.Step 2: Check syntax correctness
Onlydf.drop_duplicates()is valid syntax; brackets or braces are incorrect.Final Answer:
df.drop_duplicates() -> Option CQuick Check:
Use parentheses to call methods [OK]
- Using square brackets instead of parentheses
- Using a non-existent method name
- Using curly braces instead of parentheses
df below, what will df.drop_duplicates(subset=['Name']) return?import pandas as pd
data = {'Name': ['Anna', 'Bob', 'Anna', 'Cody'], 'Age': [25, 30, 25, 22]}
df = pd.DataFrame(data)Solution
Step 1: Understand subset parameter
Usingsubset=['Name']means duplicates are checked only on the 'Name' column.Step 2: Identify duplicates by 'Name'
'Anna' appears twice; only the first occurrence is kept, others dropped.Final Answer:
[{'Name': 'Anna', 'Age': 25}, {'Name': 'Bob', 'Age': 30}, {'Name': 'Cody', 'Age': 22}] -> Option AQuick Check:
Duplicates dropped by 'Name' column [OK]
- Not using subset and dropping all duplicates
- Keeping all duplicates instead of first
- Confusing which rows are dropped
df?df.drop_duplicates(inplace=True)
After running it, duplicates still appear in
df. Why?Solution
Step 1: Check inplace parameter usage
inplace=Truemodifies the original DataFrame, so no reassignment needed.Step 2: Consider DataFrame content
If duplicates still appear, likely the DataFrame had no duplicates to remove.Final Answer:
The DataFrame has no duplicates to remove -> Option AQuick Check:
inplace=True modifies original; no duplicates means no change [OK]
- Assuming inplace=True does nothing
- Thinking drop_duplicates always changes data
- Not verifying if duplicates exist
df with columns ['ID', 'Name', 'Score']. Some rows have duplicate ID values but different Score. How do you keep only the row with the highest Score for each ID?Solution
Step 1: Sort DataFrame by Score descending
Sorting by 'Score' descending puts highest scores first for each ID.Step 2: Drop duplicates by ID keeping first
After sorting, dropping duplicates by 'ID' keeps the first (highest score) row per ID.Final Answer:
df.sort_values('Score', ascending=False).drop_duplicates(subset=['ID']) -> Option DQuick Check:
Sort then drop duplicates keeps highest score per ID [OK]
- Not sorting before dropping duplicates
- Dropping duplicates on wrong column
- Using keep='last' without sorting
Ready to prove it?
Pass the test and this pattern moves unknown
