Bird
Raised Fist0
Pandasdata~10 mins

Counting duplicates in Pandas - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Counting duplicates
Start with DataFrame
↓
Identify duplicate rows
↓
Count duplicates per row or overall
↓
Output counts or filtered DataFrame
↓
End
We start with a DataFrame, find which rows are duplicates, count them, and then output the counts or filtered data.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({'A':[1,2,2,3,3,3], 'B':[5,6,6,7,7,7]})
dup_counts = df.duplicated(keep=False).sum()
This code creates a DataFrame and counts how many rows are duplicates.
Execution Table
StepActionDataFrame StateDuplicates IdentifiedCount Result
1Create DataFrame[{'A':1,'B':5},{'A':2,'B':6},{'A':2,'B':6},{'A':3,'B':7},{'A':3,'B':7},{'A':3,'B':7}]None yetNone yet
2Check duplicates with keep=FalseSame as step 1[False, True, True, True, True, True]None yet
3Sum True values for duplicatesSame as step 1[False, True, True, True, True, True]5
4Output total duplicate countSame as step 1[False, True, True, True, True, True]5
💡 All rows checked; total duplicates counted as 5
Variable Tracker
VariableStartAfter Step 2After Step 3Final
dfEmpty[{'A':1,'B':5},{'A':2,'B':6},{'A':2,'B':6},{'A':3,'B':7},{'A':3,'B':7},{'A':3,'B':7}]SameSame
dup_maskNone[False, True, True, True, True, True]SameSame
dup_countsNoneNone55
Key Moments - 3 Insights
Why does duplicated(keep=False) mark all duplicates as True, not just some?
Using keep=False marks every occurrence of a duplicate row as True, not just the later ones. See execution_table step 2 where all duplicates are True.
Why is the first row marked False even if there are duplicates?
The first row is unique in this example, so it's False. Only rows with exact duplicates get True. Check execution_table step 2 for the mask.
How does sum() count duplicates from the boolean mask?
True counts as 1 and False as 0, so sum() adds all True values to get total duplicates. See execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the duplicate mask for the third row?
AFalse
BTrue
CNone
DError
💡 Hint
Check the 'Duplicates Identified' column at step 2 for the third row.
At which step does the code calculate the total number of duplicate rows?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look for the step where 'Count Result' shows a number.
If we change keep=False to keep='first' in duplicated(), how would the duplicate mask change at step 2?
AAll duplicates marked True
BOnly first occurrence True
COnly later duplicates True
DNo duplicates marked True
💡 Hint
Remember 'keep=first' marks duplicates except the first occurrence as True.
Concept Snapshot
Counting duplicates in pandas:
- Use df.duplicated(keep=False) to mark all duplicates True
- Sum the boolean mask to count duplicates
- keep='first' or 'last' marks only some duplicates
- Useful to find repeated rows in data
- Returns boolean Series for filtering or counting
Full Transcript
We start with a DataFrame containing some repeated rows. Using pandas duplicated() with keep=False marks all duplicates as True in a boolean mask. Summing this mask counts how many rows are duplicates. This helps identify repeated data. The mask shows True for duplicates and False for unique rows. Changing keep parameter changes which duplicates are marked. This step-by-step trace shows how pandas counts duplicates clearly.

Practice

(1/5)
1.

What does the duplicated() function in pandas do?

easy
A. It counts how many times each value appears in a column.
B. It removes all duplicate rows from the DataFrame.
C. It marks duplicate rows as True and unique rows as False.
D. It sorts the DataFrame by duplicate values.

Solution

  1. Step 1: Understand the purpose of duplicated()

    The duplicated() function checks each row and marks it True if it is a duplicate of a previous row, otherwise False.
  2. Step 2: Compare with other functions

    Unlike drop_duplicates() which removes duplicates, duplicated() only marks them. value_counts() counts values, not duplicates.
  3. Final Answer:

    It marks duplicate rows as True and unique rows as False. -> Option C
  4. Quick Check:

    duplicated() = True/False mask [OK]
Hint: duplicated() flags duplicates, does not remove them [OK]
Common Mistakes:
  • Thinking duplicated() removes duplicates
  • Confusing duplicated() with value_counts()
  • Assuming duplicated() sorts data
2.

Which of the following is the correct syntax to count duplicate rows in a pandas DataFrame df?

?
easy
A. df.duplicated().sum()
B. df.duplicate().count()
C. df.value_counts().duplicated()
D. df.count_duplicates()

Solution

  1. Step 1: Identify correct function names

    The correct function to find duplicates is duplicated(). There is no duplicate() or count_duplicates() in pandas.
  2. Step 2: Count duplicates using sum()

    duplicated() returns a boolean Series. Using sum() counts how many True values (duplicates) exist.
  3. Final Answer:

    df.duplicated().sum() -> Option A
  4. Quick Check:

    duplicated() + sum() = count duplicates [OK]
Hint: Use duplicated() then sum() to count duplicates [OK]
Common Mistakes:
  • Using wrong function names like duplicate()
  • Trying to count duplicates with value_counts() directly
  • Using count() instead of sum() on boolean Series
3.

Given the DataFrame df below, what is the output of df.duplicated().sum()?

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 2, 3, 1], 'B': ['x', 'y', 'y', 'z', 'x']})
print(df.duplicated().sum())
medium
A. 3
B. 2
C. 1
D. 0

Solution

  1. Step 1: Identify duplicate rows

    Rows 0 and 4 are identical (A=1, B='x'), and rows 1 and 2 are identical (A=2, B='y'). The first occurrence is not counted as duplicate.
  2. Step 2: Count duplicates marked True

    Row 2 and row 4 are duplicates (second occurrences), so duplicated() marks these two rows True. Summing gives 2.
  3. Final Answer:

    2 -> Option B
  4. Quick Check:

    Two duplicate rows found = 2 [OK]
Hint: duplicated() counts second+ occurrences only [OK]
Common Mistakes:
  • Counting all duplicates including first occurrence
  • Confusing duplicated() with value_counts()
  • Ignoring that duplicated() marks only later duplicates
4.

What is wrong with this code to count duplicates in DataFrame df?

duplicates = df.duplicated.count()
medium
A. duplicated is a method and needs parentheses before count()
B. count() cannot be used on duplicated() output
C. duplicated() does not exist in pandas
D. sum() should be used instead of count()

Solution

  1. Step 1: Check method call syntax

    duplicated is a method and must be called with parentheses: duplicated().
  2. Step 2: Understand method chaining

    Without parentheses, df.duplicated.count() tries to access count attribute of the method itself, causing error. Correct is df.duplicated().count(), but this counts all rows, not duplicates.
  3. Final Answer:

    duplicated is a method and needs parentheses before count() -> Option A
  4. Quick Check:

    Call duplicated() with () before count() [OK]
Hint: Always use parentheses to call duplicated() method [OK]
Common Mistakes:
  • Forgetting parentheses on duplicated()
  • Using count() instead of sum() to count duplicates
  • Assuming duplicated is a property, not a method
5.

You have a DataFrame df with a column 'Category'. You want to find which categories appear more than once and how many times. Which code snippet correctly does this?

?
hard
A. df['Category'].count_duplicates()
B. df.duplicated('Category').sum()
C. df['Category'].duplicated().count()
D. df['Category'].value_counts()[df['Category'].value_counts() > 1]

Solution

  1. Step 1: Use value_counts() to count category occurrences

    value_counts() counts how many times each category appears.
  2. Step 2: Filter categories with counts greater than 1

    Using boolean indexing [value_counts() > 1] selects only categories appearing more than once.
  3. Final Answer:

    df['Category'].value_counts()[df['Category'].value_counts() > 1] -> Option D
  4. Quick Check:

    value_counts() + filter > 1 = repeated categories [OK]
Hint: Use value_counts() then filter counts > 1 [OK]
Common Mistakes:
  • Using duplicated() on a column returns booleans, not counts
  • Trying to call non-existent count_duplicates()
  • Using count() on duplicated() output incorrectly
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