Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Input:
+-------------+---------+---------------------+
| customer_id | name    | email               |
+-------------+---------+---------------------+
| 1           | Ella    | emily@example.com   |
| 2           | David   | michael@example.com |
| 3           | Zachary | sarah@example.com   |
| 4           | Alice   | john@example.com    |
| 5           | Finn    | john@example.com    |
| 6           | Violet  | alice@example.com   |
+-------------+---------+---------------------+
Output: 
+-------------+---------+---------------------+
| customer_id | name    | email               |
+-------------+---------+---------------------+
| 1           | Ella    | emily@example.com   |
| 2           | David   | michael@example.com |
| 3           | Zachary | sarah@example.com   |
| 4           | Alice   | john@example.com    |
| 6           | Violet  | alice@example.com   |
+-------------+---------+---------------------+
Explanation:
Alic (customer_id = 4) and Finn (customer_id = 5) both use john@example.com, so only the first occurrence of this email is retained.

## Solution

### Method 1 โ€“ pandas drop_duplicates

#### Intuition

To remove duplicate rows based on the `email` column and keep only the first occurrence, we can use the `drop_duplicates` method in pandas, specifying the `email` column and `keep='first'`.

#### Approach

1. Use `drop_duplicates` on the DataFrame, specifying `subset=['email']` and `keep='first'`.
2. Return the resulting DataFrame, sorted by `customer_id` if required.

#### Code

1
2
3
4
import pandas as pd

def drop_duplicate_rows(customers: pd.DataFrame) -> pd.DataFrame:
    return customers.drop_duplicates(subset=['email'], keep='first')
#### Complexity - โฐ Time complexity: `O(n)`, where n is the number of rows in the DataFrame. - ๐Ÿงบ Space complexity: `O(n)`, for the output DataFrame.