Sitemap

Data Cleaning in Python

4 min readDec 21, 2022

--

Press enter or click to view image in full size

Data cleaning is an essential process in the data analysis workflow. It involves identifying and correcting errors, inconsistencies, and missing values in the data. Data cleaning is crucial for accurate and meaningful analysis and modeling.

In this tutorial, we will learn how to perform data cleaning in Python using built-in functions and manual methods. We will also use some visualization techniques to understand and explore the data better.

Built-in Functions

Python provides several built-in functions and libraries that can be used to clean data effectively. Some of the commonly used functions and libraries are:

pandas: A powerful library for data manipulation and analysis. It provides several functions for cleaning and preprocessing data.

numpy: A library for scientific computing. It provides functions for handling missing values and performing mathematical operations on arrays.

sklearn: A library for machine learning. It provides functions for scaling and normalizing data.

Let’s start by importing the necessary libraries:

import pandas as pd
import numpy as np
from sklearn import preprocessing

Handling Missing Values

One of the common problems in real-world data is missing values. There can be various reasons for missing values, such as data not being recorded, data being lost, or data being incomplete.

Pandas provides several functions for handling missing values:

isnull(): Returns a boolean array indicating whether each element in the dataframe is null or not.

notnull(): Returns a boolean array indicating whether each element in the dataframe is not null or null.

dropna(): Drops rows or columns with null values.

fillna(): Fills null values with a specified value.

Let’s use the built-in Titanic dataset from seaborn library to demonstrate these functions:

import seaborn as sns

# Load the Titanic dataset
df = sns.load_dataset('titanic')

# Check for missing values
print(df.isnull().sum())

# Drop rows with missing values
df_drop = df.dropna()

# Fill missing values with 0
df_fill = df.fillna(0)

Handling Outliers

Outliers are data points that are significantly different from the rest of the data. Outliers can be caused by errors in data collection, measurement, or entry. They can distort the overall distribution of the data and affect the results of the analysis and modeling.

Get Muhammet miraç Yüzaklı’s stories in your inbox

Join Medium for free to get updates from this writer.

One way to identify and handle outliers is by using the Z-score method. The Z-score is the number of standard deviations a data point is from the mean. Data points with a Z-score greater than 3 or less than -3 are considered as outliers.

We can use the scipy library to calculate the Z-score and identify the outliers:

from scipy import stats

# Calculate the Z-score of each data point
z = np.abs(stats.zscore(df))

# Identify the outliers
outliers = np.where(z > 3)

# Drop the outliers
df_clean = df[(z < 3).all(axis=1)]

Normalization and Scaling

Normalization and scaling are techniques used to transform the data to a common scale. Normalization scales the data between 0 and 1, while scaling scales the data to have a mean of 0 and a standard deviation of 1.

We can use the MinMaxScaler and StandardScaler functions from the sklearn.preprocessing library to normalize and scale the data, respectively:

# Normalize the data
scaler = preprocessing.MinMaxScaler()
df_norm = pd.DataFrame(scaler.fit_transform(df), columns=df.columns)

# Scale the data
scaler = preprocessing.StandardScaler()
df_scaled = pd.DataFrame(scaler.fit_transform(df), columns=df.columns)

Manual Methods

In addition to the built-in functions, we can also use manual methods for data cleaning. Some of the common manual methods are:

Checking for errors and inconsistencies: We can manually check the data for errors and inconsistencies, such as incorrect data types, incorrect values, and spelling mistakes.

Fixing errors and inconsistencies: We can fix the errors and inconsistencies by manually replacing or correcting the values.

Exploratory Data Analysis (EDA): We can use visualization techniques to explore and understand the data better. Some of the common visualization techniques are:

Univariate plots: Plots for analyzing individual variables. Examples include histograms, bar plots, and box plots.

Multivariate plots: Plots for analyzing the relationships between variables. Examples include scatter plots and pair plots.

Let’s use the Titanic dataset to demonstrate these manual methods:

import matplotlib.pyplot as plt

# Check for errors and inconsistencies
df.info()
df.describe()

# Fix errors and inconsistencies
df['age'].fillna(df['age'].median(), inplace=True)
df['fare'] = df['fare'].astype(int)

# Explore the data
df.hist(figsize=(10, 10))
plt.show()

# Plot univariate plots
df['age'].plot.hist()
plt.show()

df['fare'].plot.box()
plt.show()

# Plot multivariate plots
sns.scatterplot(x='age', y='fare', data=df)
plt.show()

sns.pairplot(df)
plt.show()

Conclusion

In this tutorial, we learned how to perform data cleaning in Python using built-in functions and manual methods. We saw how to handle missing values, identify and remove outliers, normalize and scale the data, and explore the data using visualization techniques. Data cleaning is an essential step in the data analysis workflow, and using the right tools and techniques can help us clean and prepare the data for accurate and meaningful analysis and modeling.

Linkedln: https://www.linkedin.com/in/muhammet-mira%C3%A7-0564631a0/

UpWork: https://www.upwork.com/freelancers/~0178f4cf3eb93b5f83

Github: https://github.com/miracyuzakli

--

--

Muhammet miraç Yüzaklı
Muhammet miraç Yüzaklı

Written by Muhammet miraç Yüzaklı

Hi there! I'm Miraç Yüzaklı, a passionate writer in data science, Python, and computer science. Let's simplify complex concepts and explore tech together!