Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Duplicate Data Handling

Pandas Duplicate Data Handling

Duplicate data is a common problem in data analysis that affects the accuracy of statistical results. Pandas provides complete functionality for detecting and handling duplicate data.


Detect duplicate data

The duplicated method

Example

import

pandas

as

pd

Create a DataFrame containing duplicate rows

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Wang Wu"

,

"Zhang San"

,

"Li Si"

,

"Zhao Liu"

]

,

   

"Age"

:

[

25

,

30

,

28

,

25

,

30

,

35

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Guangzhou"

,

"Beijing"

,

"Shenzhen"

,

"Beijing"

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Detect duplicate rows (by default, marking starts with the first occurrence, keep='first')

print

(

"Detect duplicate rows:"

)

print

(

df.

duplicated

(

)

)

print

(

)

Count the number of duplicate rows

print

(

f

"Number of duplicate rows: {df.duplicated().sum()}"

)

print

(

)

Detect duplicates in specific columns

print

(

"Detect duplicates by the 'name' column:"

)

print

(

df.

duplicated

(

subset

=

[

"Name"

]

)

)

The keep parameter

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Zhang San"

,

"Wang Wu"

,

"Li Si"

]

,

   

"Age"

:

[

25

,

30

,

25

,

28

,

30

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

keep='first': keep the first occurrence (default)

print

(

"keep='first' (default):"

)

print

(

df.

duplicated

(

keep

=

"first"

)

)

print

(

)

keep='last': keep the last occurrence

print

(

"keep='last':"

)

print

(

df.

duplicated

(

keep

=

"last"

)

)

print

(

)

keep=False: mark all duplicates (keep none)

print

(

"keep=False (mark all duplicates):"

)

print

(

df.

duplicated

(

keep

=

False

)

)


Remove duplicate data

Basic usage of drop_duplicates

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Zhang San"

,

"Wang Wu"

,

"Li Si"

]

,

   

"Age"

:

[

25

,

30

,

25

,

28

,

30

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Beijing"

,

"Guangzhou"

,

"Shenzhen"

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Remove duplicate rows (by default, keep the first)

print

(

"Remove duplicate rows (keep the first):"

)

print

(

df.

drop_duplicates

(

)

)

print

(

)

Keep the last one

print

(

"Remove duplicate rows (keep the last):"

)

print

(

df.

drop_duplicates

(

keep

=

"last"

)

)

print

(

)

Keep no duplicate rows

print

(

"Remove all duplicate rows:"

)

print

(

df.

drop_duplicates

(

keep

=

False

)

)

Remove duplicates by column

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Zhang San"

,

"Wang Wu"

]

,

   

"Age"

:

[

25

,

30

,

35

,

28

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Beijing"

,

"Guangzhou"

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Deduplicate by a single column

print

(

"Deduplicate by the 'name' column:"

)

print

(

df.

drop_duplicates

(

subset

=

[

"Name"

]

)

)

print

(

)

Deduplicate by a combination of columns

print

(

"Deduplicate by the 'name'+'city' combination:"

)

print

(

df.

drop_duplicates

(

subset

=

[

"Name"

,

"City"

]

)

)

print

(

)

Keep the row with the largest value in a specific column

print

(

"Group by 'name' and keep the row with the greatest age:"

)

print

(

df.

sort_values

(

"Age"

,

ascending

=

False

)

.

drop_duplicates

(

subset

=

[

"Name"

]

,

keep

=

"first"

)

)


Practical example: data cleaning

Comprehensive example

Example

import

pandas

as

pd

import

numpy

as

np

Create simulated order data (including duplicates)

orders

=

pd.

DataFrame

(

{

   

"order_id"

:

[

"O001"

,

"O002"

,

"O001"

,

"O003"

,

"O002"

,

"O004"

]

,

   

"Customer ID"

:

[

"C001"

,

"C002"

,

"C001"

,

"C003"

,

"C002"

,

"C004"

]

,

   

"product"

:

[

"iPhone"

,

"MacBook"

,

"iPhone"

,

"iPad"

,

"AirPods"

,

"Apple Watch"

]

,

   

"amount"

:

[

8000

,

12000

,

8000

,

5000

,

1500

,

3000

]

,

   

"date"

:

[

"2024-01-01"

,

"2024-01-02"

,

"2024-01-01"

,

"2024-01-03"

,

"2024-01-02"

,

"2024-01-04"

]

}

)

print

(

"Original order data:"

)

print

(

orders

)

print

(

)

1. Detect duplicate orders

print

(

"Duplicate order detection:"

)

duplicates

=

orders

[

orders.

duplicated

(

subset

=

[

"order_id"

]

,

keep

=

False

)

]

print

(

duplicates

)

print

(

)

2. Remove completely duplicate orders

orders_clean

=

orders.

drop_duplicates

(

)

print

(

"After removing complete duplicates:"

)

print

(

f

"Original {len(orders)} rows -> {len(orders_clean)} rows"

)

print

(

)

3. Deduplicate by order_id, keeping the latest

Assume the last entry is the latest

orders_clean

=

orders.

sort_values

(

"date"

)

.

drop_duplicates

(

    subset

=

[

"order_id"

]

,

    keep

=

"last"

)

.

sort_index

(

)

print

(

"Deduplicate by order_id (keep the latest):"

)

print

(

orders_clean

)


Advanced usage

Keep specific rows by group

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"customer"

:

[

"A"

,

"A"

,

"A"

,

"B"

,

"B"

,

"B"

]

,

   

"Month"

:

[

"01"

,

"02"

,

"03"

,

"01"

,

"02"

,

"03"

]

,

   

"spending"

:

[

100

,

200

,

150

,

300

,

250

,

280

]

}

)

print

(

"Original data:"

)

print

(

df

)

print

(

)

Keep the month with the highest spending for each customer

print

(

"The month with the highest spending for each customer:"

)

result

=

df.

sort_values

(

"spending"

,

ascending

=

False

)

.

drop_duplicates

(

    subset

=

[

"customer"

]

,

    keep

=

"first"

)

.

sort_values

(

"customer"

)

print

(

result

)

print

(

)

Keep the first record for each customer (by month)

print

(

"The first record for each customer:"

)

result

=

df.

sort_values

(

"Month"

)

.

drop_duplicates

(

    subset

=

[

"customer"

]

,

    keep

=

"first"

)

print

(

result

)

Mark duplicates instead of removing them

Example

import

pandas

as

pd

df

=

pd.

DataFrame

(

{

   

"Name"

:

[

"Zhang San"

,

"Li Si"

,

"Zhang San"

,

"Wang Wu"

,

"Li Si"

]

,

   

"City"

:

[

"Beijing"

,

"Shanghai"

,

"Beijing"

,

"Guangzhou"

,

"Shenzhen"

]

}

)

Add a duplicate-mark column

df

[

"is_duplicate"

]

=

df.

duplicated

(

subset

=

[

"Name"

]

,

keep

=

False

)

print

(

"Mark duplicate rows:"

)

print

(

df

)

print

(

)

Or use groupby to mark

df

[

"repeat_count"

]

=

df.

groupby

(

"Name"

)

[

"Name"

]

.

transform

(

"count"

)

df

[

"is_first"

]

=

~

df.

duplicated

(

subset

=

[

"Name"

]

,

keep

=

"first"

)

print

(

"Count repeats by group:"

)

print

(

df

)


Notes

1. Distinguish "complete duplicates" from "partial duplicates"

A complete duplicate means all column values are the same, while a partial duplicate means specific columns are the same. Use the subset parameter to specify the columns used to judge duplicates.

2. Choosing a retention strategy

Choose to keep the first, the last, or none according to business needs. Which one you keep may affect later analysis results.

3. The effect of data types

Data types are considered when judging duplicates; for example, the integer 1 and the float 1.0 are treated as different.

Before removing duplicate data, it is recommended to first analyze the causes and distribution of the duplicates to ensure that the removal does not lose important information.