Bird
Raised Fist0
Data Analysis Pythondata~10 mins

Removing duplicates (drop_duplicates) in Data Analysis Python - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Removing duplicates (drop_duplicates)
Start with DataFrame
↓
Check each row for duplicates
↓
Mark duplicates as True/False
↓
Keep first occurrence, remove others
↓
Return DataFrame without duplicates
↓
End
The process checks each row in the data, marks duplicates, keeps the first occurrence, and removes the rest to return a clean DataFrame.
Execution Sample
Data Analysis Python
import pandas as pd

df = pd.DataFrame({
    'Name': ['Anna', 'Bob', 'Anna', 'Cody'],
    'Age': [25, 30, 25, 22]
})

clean_df = df.drop_duplicates()
This code creates a DataFrame with duplicate rows and removes duplicates using drop_duplicates.
Execution Table
StepRow IndexRow DataIs Duplicate?ActionResulting DataFrame Rows
10{'Name': 'Anna', 'Age': 25}NoKeep[0]
21{'Name': 'Bob', 'Age': 30}NoKeep[0, 1]
32{'Name': 'Anna', 'Age': 25}YesRemove[0, 1]
43{'Name': 'Cody', 'Age': 22}NoKeep[0, 1, 3]
5----Final DataFrame has rows with indices [0, 1, 3]
💡 All rows checked; duplicates removed except first occurrences.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
df[4 rows][4 rows][4 rows][4 rows][4 rows][4 rows]
clean_dfN/AN/AN/A[3 rows, duplicates removed][3 rows][3 rows]
Key Moments - 2 Insights
Why does drop_duplicates keep the first occurrence and remove later ones?
drop_duplicates by default keeps the first occurrence to preserve the original order and only remove repeated rows after that, as shown in execution_table rows 3 and 4.
Does drop_duplicates remove rows with any difference or only exact duplicates?
It removes only exact duplicates where all column values match, as seen in row 2 and 3 where the 'Anna' rows are identical and one is removed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, which row is identified as a duplicate and removed?
ARow with index 1
BRow with index 3
CRow with index 2
DRow with index 0
💡 Hint
Check the 'Is Duplicate?' and 'Action' columns in execution_table row 3.
At which step does the DataFrame first lose a row due to duplicate removal?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Resulting DataFrame Rows' column in execution_table rows 2 and 3.
If drop_duplicates was called with keep='last', which row would be removed instead?
ARow with index 0
BRow with index 1
CRow with index 2
DRow with index 3
💡 Hint
drop_duplicates with keep='last' keeps the last occurrence, so the first duplicate is removed.
Concept Snapshot
drop_duplicates removes duplicate rows from a DataFrame.
By default, it keeps the first occurrence and removes later duplicates.
Duplicates are rows where all column values match exactly.
Use keep='last' to keep the last occurrence instead.
Returns a new DataFrame without duplicates.
Full Transcript
This visual execution shows how pandas drop_duplicates works step-by-step. Starting with a DataFrame of four rows, it checks each row for duplicates. The first 'Anna' row is kept. The second 'Anna' row is detected as a duplicate and removed. Other unique rows are kept. The final DataFrame has three rows with duplicates removed. This helps clean data by removing repeated entries while keeping the original order.

Practice

(1/5)
1. What does the drop_duplicates() function do in a pandas DataFrame?
easy
A. Fills missing values with zeros
B. Removes repeated rows based on all columns by default
C. Sorts the DataFrame rows in ascending order
D. Changes the data type of columns

Solution

  1. Step 1: Understand the function purpose

    drop_duplicates() is used to remove repeated rows in a DataFrame.
  2. Step 2: Default behavior

    By default, it checks all columns to find duplicates and keeps the first occurrence.
  3. Final Answer:

    Removes repeated rows based on all columns by default -> Option B
  4. Quick Check:

    drop_duplicates() removes repeated rows [OK]
Hint: Remember: drop_duplicates removes repeated rows [OK]
Common Mistakes:
  • Thinking it sorts data
  • Confusing with fillna()
  • Assuming it changes data types
2. Which of the following is the correct syntax to remove duplicate rows from a DataFrame df?
easy
A. df.drop_duplicates[]
B. df.remove_duplicates()
C. df.drop_duplicates()
D. df.drop_duplicates{}

Solution

  1. Step 1: Identify correct method call

    The method to remove duplicates is drop_duplicates(), called with parentheses.
  2. Step 2: Check syntax correctness

    Only df.drop_duplicates() is valid syntax; brackets or braces are incorrect.
  3. Final Answer:

    df.drop_duplicates() -> Option C
  4. Quick Check:

    Use parentheses to call methods [OK]
Hint: Use parentheses () to call drop_duplicates method [OK]
Common Mistakes:
  • Using square brackets instead of parentheses
  • Using a non-existent method name
  • Using curly braces instead of parentheses
3. Given the DataFrame 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)
medium
A. [{'Name': 'Anna', 'Age': 25}, {'Name': 'Bob', 'Age': 30}, {'Name': 'Cody', 'Age': 22}]
B. [{'Name': 'Anna', 'Age': 25}, {'Name': 'Anna', 'Age': 25}, {'Name': 'Bob', 'Age': 30}, {'Name': 'Cody', 'Age': 22}]
C. [{'Name': 'Bob', 'Age': 30}, {'Name': 'Cody', 'Age': 22}]
D. [{'Name': 'Anna', 'Age': 25}, {'Name': 'Bob', 'Age': 30}]

Solution

  1. Step 1: Understand subset parameter

    Using subset=['Name'] means duplicates are checked only on the 'Name' column.
  2. Step 2: Identify duplicates by 'Name'

    'Anna' appears twice; only the first occurrence is kept, others dropped.
  3. Final Answer:

    [{'Name': 'Anna', 'Age': 25}, {'Name': 'Bob', 'Age': 30}, {'Name': 'Cody', 'Age': 22}] -> Option A
  4. Quick Check:

    Duplicates dropped by 'Name' column [OK]
Hint: Use subset to check duplicates on specific columns [OK]
Common Mistakes:
  • Not using subset and dropping all duplicates
  • Keeping all duplicates instead of first
  • Confusing which rows are dropped
4. What is wrong with this code snippet to remove duplicates from DataFrame df?
df.drop_duplicates(inplace=True)

After running it, duplicates still appear in df. Why?
medium
A. The DataFrame has no duplicates to remove
B. drop_duplicates() does not modify the original DataFrame even with inplace=True
C. The DataFrame was not reassigned and inplace=True is ignored
D. The inplace parameter is misspelled

Solution

  1. Step 1: Check inplace parameter usage

    inplace=True modifies the original DataFrame, so no reassignment needed.
  2. Step 2: Consider DataFrame content

    If duplicates still appear, likely the DataFrame had no duplicates to remove.
  3. Final Answer:

    The DataFrame has no duplicates to remove -> Option A
  4. Quick Check:

    inplace=True modifies original; no duplicates means no change [OK]
Hint: Check if DataFrame actually has duplicates before drop_duplicates [OK]
Common Mistakes:
  • Assuming inplace=True does nothing
  • Thinking drop_duplicates always changes data
  • Not verifying if duplicates exist
5. You have a DataFrame 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?
hard
A. Use df.drop_duplicates(subset=['Score'])
B. Use df.drop_duplicates(subset=['ID']) without sorting
C. Use df.drop_duplicates(keep='last') without sorting
D. Use df.sort_values('Score', ascending=False).drop_duplicates(subset=['ID'])

Solution

  1. Step 1: Sort DataFrame by Score descending

    Sorting by 'Score' descending puts highest scores first for each ID.
  2. Step 2: Drop duplicates by ID keeping first

    After sorting, dropping duplicates by 'ID' keeps the first (highest score) row per ID.
  3. Final Answer:

    df.sort_values('Score', ascending=False).drop_duplicates(subset=['ID']) -> Option D
  4. Quick Check:

    Sort then drop duplicates keeps highest score per ID [OK]
Hint: Sort by score descending before drop_duplicates to keep max [OK]
Common Mistakes:
  • Not sorting before dropping duplicates
  • Dropping duplicates on wrong column
  • Using keep='last' without sorting
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard