Handling Duplicates and Outliers in Datasets

Topic Overview and Actualization

Today, we target duplicates and outliers to clean our data for more accurate analysis.

Understanding Duplicates in Data

Let's consider a dataset from a school containing students' details. If a student's information appears more than once, that is regarded as a duplicate. Duplicates distort data, leading to inaccurate statistics.

Python Tools for Handling Duplicates

pandas library provides efficient and easy-to-use functions for dealing with duplicates.

Python
import pandas as pd

# Create DataFrame
data = {'Name': ['John', 'Anna', 'Peter', 'John', 'Anna'],
        'Age': [16, 15, 13, 16, 15],
        'Grade': [9, 10, 7, 9, 10]}
df = pd.DataFrame(data)

The duplicated() function flags duplicate rows:

Python
print(df.duplicated())
'''Output:
0    False
1    False
2    False
3     True
4     True
dtype: bool
'''

A True in the output denotes a row in the DataFrame that repeats. Note, that one of the repeating rows is marked as False – to keep one in case we decide to drop all the duplicates.

The drop_duplicates() function helps to discard these duplicates:

Python
df = df.drop_duplicates()
print(df)
'''Output:
    Name  Age  Grade
0   John   16      9
1   Anna   15     10
2  Peter   13      7
'''

There is no more duplicates, cool!

Understanding Outliers in Data

An outlier is a data point significantly different from others. In our dataset of primary school students' ages, we might find an age like 98 — this would be an outlier.

Identifying Outliers

Outliers can be detected visually using tools like box plots, scatter plots, or statistical methods such as Z-score or IQR. Let's consider a data point that's significantly different from the rest. We'll use the IQR method for identifying outliers.

As a short reminder, we consider a value an outlier if it is either more than 1.5 * IQR less than Q1 (first quartile) or more than 1.5 * IQR greater than Q3 (third quartile).

Python Tools for Handling Outliers

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal