When you have repeated data, you often want to keep only some of it. This helps to clean your data and avoid confusion.
Keeping first vs last vs none in Pandas
DataFrame.drop_duplicates(subset=None, keep='first', inplace=False)
subset lets you choose columns to check for duplicates.
keep can be 'first', 'last', or False (none).
df.drop_duplicates(keep='first')df.drop_duplicates(keep='last')df.drop_duplicates(keep=False)This code shows how to keep first, last, or no duplicates in a simple table of names and scores.
import pandas as pd data = {'Name': ['Anna', 'Bob', 'Anna', 'Bob', 'Cathy'], 'Score': [85, 90, 85, 95, 88]} df = pd.DataFrame(data) print('Original DataFrame:') print(df) print('\nKeep first duplicates:') print(df.drop_duplicates(keep='first')) print('\nKeep last duplicates:') print(df.drop_duplicates(keep='last')) print('\nKeep none (remove all duplicates):') print(df.drop_duplicates(keep=False))
Using keep=False removes all rows that have duplicates, leaving only unique rows.
If you want to check duplicates only on some columns, use the subset parameter.
Setting inplace=True changes the original DataFrame without making a copy.
Keep='first' keeps the first duplicate and removes later ones.
Keep='last' keeps the last duplicate and removes earlier ones.
Keep=False removes all duplicates, keeping only unique rows.
Practice
In pandas, what does keep='first' do when removing duplicates?
Solution
Step 1: Understand the meaning of keep='first'
This option keeps the first row of each set of duplicates and removes the later ones.Step 2: Compare with other options
Unlike keep='last' which keeps the last occurrence, keep='first' keeps the earliest one.Final Answer:
Keeps the first occurrence of each duplicate and removes the rest -> Option AQuick Check:
keep='first' = Keep first duplicate [OK]
- Confusing keep='first' with keep='last'
- Thinking keep='first' removes all duplicates
- Assuming keep='first' keeps all duplicates
Which of the following is the correct syntax to remove duplicates in a pandas DataFrame df keeping only the last occurrence?
df._____('column_name', keep='last')Solution
Step 1: Identify the pandas method for removing duplicates
The correct method isdrop_duplicatesto remove duplicate rows.Step 2: Confirm syntax for keeping last occurrence
Usingkeep='last'insidedrop_duplicateskeeps the last duplicate row.Final Answer:
drop_duplicates -> Option CQuick Check:
Method to remove duplicates = drop_duplicates [OK]
- Using non-existent methods like remove_duplicates
- Confusing method names with similar words
- Forgetting to specify keep='last'
What will be the output of the following code?
import pandas as pd
data = {'A': [1, 2, 2, 3, 3, 3], 'B': ['x', 'y', 'y', 'z', 'z', 'z']}
df = pd.DataFrame(data)
result = df.drop_duplicates(keep=False)
print(result)Solution
Step 1: Understand keep=False behavior
Usingkeep=Falseremoves all duplicates, keeping only rows that appear once.Step 2: Identify unique rows in the DataFrame
In the data, only the row with A=1 and B='x' is unique; others appear multiple times.Final Answer:
Rows with unique values only, no duplicates -> Option AQuick Check:
keep=False = Keep only unique rows [OK]
- Thinking keep=False keeps first or last duplicates
- Expecting some duplicates to remain
- Confusing output with keep='first' or keep='last'
Consider this code snippet:
import pandas as pd
data = {'col': [1, 1, 2, 2, 3]}
df = pd.DataFrame(data)
result = df.drop_duplicates(keep='middle')
print(result)What is the error in this code?
Solution
Step 1: Check the 'keep' parameter values
The valid values for 'keep' are 'first', 'last', or False. 'middle' is invalid.Step 2: Identify the error raised by invalid 'keep'
Using 'middle' causes a ValueError because pandas does not recognize it.Final Answer:
Invalid value for the 'keep' parameter -> Option BQuick Check:
keep must be 'first', 'last', or False [OK]
- Using unsupported strings for keep
- Assuming 'middle' is valid
- Ignoring error messages
You have a DataFrame df with duplicate rows based on column 'ID'. You want to remove all duplicates completely, so only rows with unique 'ID' remain. Which code snippet achieves this?
1) df.drop_duplicates(subset=['ID'], keep='first') 2) df.drop_duplicates(subset=['ID'], keep='last') 3) df.drop_duplicates(subset=['ID'], keep=False) 4) df.drop_duplicates()
Solution
Step 1: Understand the goal
The goal is to remove all duplicates so only unique 'ID' rows remain.Step 2: Analyze each option
Options 1 and 2 keep one duplicate (first or last). Option 4 removes duplicates but keeps first by default. Only option 3 withkeep=Falseremoves all duplicates completely.Final Answer:
Option 3 -> Option DQuick Check:
keep=False removes all duplicates [OK]
- Using keep='first' or 'last' when full removal needed
- Not specifying subset for duplicate check
- Assuming default drop_duplicates removes all duplicates
Ready to prove it?
Pass the test and this pattern moves unknown
