Pandas Cleaning Data

Introduction

Pandas Cleaning Data is an important part of data analysis. Real-world datasets often contain missing values, incorrect information, duplicate records, and formatting problems. Pandas provides several functions to identify and clean these issues. In this chapter, you will learn the basics of cleaning data using Pandas.

What is Data Cleaning?

Data cleaning is the process of finding and fixing incorrect, incomplete, duplicate, or inconsistent data in a dataset.

For example, an employee dataset may contain:

  • Missing employee names.
  • Incorrect salary values.
  • Duplicate employee records.
  • Dates stored in the wrong format.
  • Extra spaces in text values.

Before analyzing data, it is important to identify and correct these problems.

Creating a DataFrame with Unclean Data

Let’s create a DataFrame containing some common data problems.

Example:

import pandas as pd

data = {
    "Name": ["Amit", "Neha", "Rahul", None, "Karan"],
    "Age": [25, 28, None, 30, 27],
    "Salary": [35000, 40000, 32000, None, 45000],
    "Department": ["IT", "HR", "Sales", "IT", "HR"]
}

df = pd.DataFrame(data)

print(df)

Output:

    Name   Age   Salary Department
0   Amit  25.0  35000.0         IT
1   Neha  28.0  40000.0         HR
2  Rahul   NaN  32000.0      Sales
3   None  30.0      NaN         IT
4  Karan  27.0  45000.0         HR

Explanation: This DataFrame contains missing values in the Name, Age, and Salary columns. We will use it to understand basic data cleaning operations.

Identifying Missing Values Using isnull()

The isnull() function checks whether values in a DataFrame are missing.

It returns:

  • True if a value is missing.
  • False if a value is available.

Example:

print(df.isnull())

Output:

    Name    Age  Salary  Department
0  False  False   False       False
1  False  False   False       False
2  False   True   False       False
3   True  False    True       False
4  False  False   False       False

Explanation: The output shows True wherever a value is missing. For example, row 2 has a missing Age, while row 3 has missing Name and Salary values.

Identifying Missing Values Using notnull()

The notnull() function checks whether values are available in a DataFrame.

It returns:

  • True if a value is not missing.
  • False if a value is missing.

Example:

print(df.notnull())

Output:

    Name    Age  Salary  Department
0   True   True    True        True
1   True   True    True        True
2   True  False    True        True
3  False   True   False        True
4   True   True    True        True

Explanation: The function returns True for available values and False for missing values.

Counting Missing Values Using isnull().sum()

You can combine isnull() with sum() to count missing values in each column.

Example:

print(df.isnull().sum())

Output:

Name          1
Age           1
Salary        1
Department    0
dtype: int64

Explanation: This result shows that the Name, Age, and Salary columns each contain one missing value. The Department column has no missing values.

Removing Missing Values Using dropna()

The dropna() function removes rows containing missing values from a DataFrame.

Example:

new_df = df.dropna()

print(new_df)

Output:

    Name   Age   Salary Department
0   Amit  25.0  35000.0         IT
1   Neha  28.0  40000.0         HR
4  Karan  27.0  45000.0         HR

Explanation: Rows 2 and 3 are removed because they contain at least one missing value. The original DataFrame df remains unchanged because the cleaned result is stored in new_df.

Filling Missing Values Using fillna()

Instead of removing rows, you can fill missing values with a specific value using the fillna() function.

Example:

new_df = df.fillna("Unknown")

print(new_df)

Output:

    Name      Age    Salary Department
0   Amit     25.0   35000.0         IT
1   Neha     28.0   40000.0         HR
2  Rahul     Unknown 32000.0      Sales
3  Unknown  30.0   Unknown         IT
4  Karan    27.0   45000.0         HR

Explanation: The fillna() function replaces missing values with "Unknown". However, using the same text value for numerical columns can change their data types. In practical projects, choose replacement values according to the type and meaning of each column.

Replacing Incorrect Values Using replace()

The replace() function is used to replace specific values in a DataFrame.

Example:

data = {
    "Name": ["Amit", "Neha", "Rahul", "Priya"],
    "Department": ["IT", "HR", "IT", "Human Resource"]
}

df = pd.DataFrame(data)

new_df = df.replace("Human Resource", "HR")

print(new_df)

Output:

    Name Department
0   Amit         IT
1   Neha         HR
2  Rahul         IT
3  Priya         HR

Explanation: The replace() function changes "Human Resource" to "HR" in the Department column.

Checking Duplicate Records Using duplicated()

The duplicated() function checks whether rows are repeated in a DataFrame.

It returns:

  • True for duplicate rows.
  • False for rows that are not duplicates.

Example:

data = {
    "Name": ["Amit", "Neha", "Rahul", "Neha"],
    "Department": ["IT", "HR", "Sales", "HR"]
}

df = pd.DataFrame(data)

print(df.duplicated())

Output:

0    False
1    False
2    False
3     True
dtype: bool

Explanation: Row 3 is marked True because it contains the same values as row 1.

Removing Duplicate Records Using drop_duplicates()

The drop_duplicates() function removes repeated rows from a DataFrame.

Example:

new_df = df.drop_duplicates()

print(new_df)

Output:

    Name Department
0   Amit         IT
1   Neha         HR
2  Rahul      Sales

Explanation: The duplicate row containing Neha and HR is removed. Only unique rows remain in the new DataFrame.

Student Task

Create a DataFrame named employees using the following data:

NameDepartmentAgeSalary
AmitIT2535000
NehaHR2840000
RahulSales2432000
PriyaIT2745000
NehaHR2840000
KaranMarketing3050000

Your Tasks:

  1. Create a Pandas DataFrame using the given employee data.
  2. Check for missing values using isnull().
  3. Count missing values in each column using isnull().sum().
  4. Check available values using notnull().
  5. Replace "Marketing" with "Marketing Department" using replace().
  6. Check duplicate records using duplicated().
  7. Remove duplicate records using drop_duplicates().
  8. Display the cleaned DataFrame.

Key Takeaways

  • Clean Data in Pandas helps improve the quality and accuracy of a dataset.
  • isnull() identifies missing values.
  • notnull() identifies available values.
  • isnull().sum() counts missing values in each column.
  • dropna() removes rows containing missing values by default.
  • fillna() replaces missing values.
  • replace() changes specific values.
  • duplicated() identifies duplicate rows.
  • drop_duplicates() removes duplicate rows.

Frequently Asked Questions (FAQs)

1. What Is Pandas Cleaning Data in Python?

Pandas Cleaning Data is the process of identifying and fixing incorrect, missing, duplicate, or inconsistent data in a dataset using Python Pandas. It helps make data accurate and ready for analysis.

2. How to Clean Data in Pandas?

You can Clean Data in Pandas using functions such as dropna(), fillna(), drop_duplicates(), and replace(). These functions help handle missing values, remove duplicate records, and correct unwanted data.

3. What Are the Most Common Pandas Data Cleaning Functions?

Common Pandas Data Cleaning functions include dropna(), fillna(), drop_duplicates(), isnull(), notnull(), replace(), and duplicated(). These functions help identify and clean unwanted data.

4. Why Is Data Cleaning Important in Python?

Python Data Cleaning is important because raw datasets may contain missing values, duplicate records, incorrect entries, and inconsistent formats. Cleaning data improves data quality and helps produce more reliable analysis results.

5. How to Remove Missing Values During Pandas Data Cleaning?

During Pandas Data Cleaning, you can use the dropna() function to remove rows or columns containing missing values. Alternatively, use fillna() to replace missing values with suitable data.

6. How to Remove Duplicate Rows in Pandas?

You can remove duplicate rows in Pandas using the drop_duplicates() function. It identifies repeated records in a DataFrame and removes them while keeping the first occurrence by default.

7. Can Pandas Handle Incorrect and Inconsistent Data?

Yes, Pandas can handle incorrect and inconsistent data using functions such as replace(), astype(), fillna(), and string methods. These tools help standardize values, correct data types, and improve dataset quality.

8. What Can We Learn About Data Cleaning in a Python Pandas Tutorial?

A Python Pandas Tutorial teaches you how to identify missing values, remove duplicate records, replace incorrect values, handle inconsistent data, and prepare datasets for accurate data analysis.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top