Drop Duplicate Rows Problem
#2882
Description
LeetCode Problem 2882.
DataFrame customers
+-------------+--------+
| Column Name | Type |
+-------------+--------+
| customer_id | int |
| name | object |
| email | object |
+-------------+--------+
There are some duplicate rows in the DataFrame based on the email column.
Write a solution to remove these duplicate rows and keep only the first occurrence.
The result format is in the following example.
Example 1:
Input:
+-------------+---------+---------------------+
| customer_id | name | email |
+-------------+---------+---------------------+
| 1 | Ella | [email protected] |
| 2 | David | [email protected] |
| 3 | Zachary | [email protected] |
| 4 | Alice | [email protected] |
| 5 | Finn | [email protected] |
| 6 | Violet | [email protected] |
+-------------+---------+---------------------+
Output:
+-------------+---------+---------------------+
| customer_id | name | email |
+-------------+---------+---------------------+
| 1 | Ella | [email protected] |
| 2 | David | [email protected] |
| 3 | Zachary | [email protected] |
| 4 | Alice | [email protected] |
| 6 | Violet | [email protected] |
+-------------+---------+---------------------+
Explanation:
Alic (customer_id = 4) and Finn (customer_id = 5) both use [email protected], so only the first occurrence of this email is retained.
Solution
Approach: drop_duplicates on email
Duplicates are judged by email only, so pass subset=['email']. The default keep='first' retains the first occurrence of each address and drops later ones, which is exactly the requirement. Without subset, rows that differ in customer_id or name would never count as duplicates.
import pandas as pd
def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame:
return customers.drop_duplicates(subset=['email'])