Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 12

Pandas Data Cleaning Essentials

This lesson is built with resources from medium.com and freecodecamp.org.

Hello! Welcome back to our module on Python Tools for AI and Data Manipulation.

In the previous lesson, we focused on loading data into Pandas DataFrames and performing an initial inspection using methods like .head(), .info(), and .describe(). You learned that .info() is particularly powerful for getting a quick summary of your data's health, often revealing two common problems: missing values and incorrect data types.

This lesson directly addresses those problems, covering the learning outcome: Perform basic data cleaning operations in Pandas including handling missing values and correcting data types. This is a critical step in any AI or data science workflow. As a software engineer, you're familiar with the principle of "garbage in, garbage out." Data cleaning is how we ensure we're not feeding garbage into our models.

1. Handling Missing Values

Your initial data inspection with .info() or df.isnull().sum() will almost always uncover missing data, represented in Pandas as NaN (Not a Number). Machine learning models cannot process NaN values, so you must handle them. There are two primary strategies: dropping them or filling them (imputation).

To get a practical look at these techniques, please read the following sections from an article on data cleaning with Pandas.

Practical Examples of Data Cleaning Using Pandas and ...

The article 'Practical Examples of Data Cleaning Using Pandas' provides clear, code-driven examples for finding and handling missing values.

Read Section 2, 'Handling Missing Values'. Below the section heading, read through handling missing values. Focus on how isnull().sum() is used to count missing values and understand the code for dropna() and fillna().

Let's break down the key ideas from the reading.

Identifying Missing Values

While .info() gives you a good overview, the most direct way to count missing values per column is:

# Assuming 'df' is your DataFrame
missing_counts = df.isnull().sum()
print(missing_counts[missing_counts > 0]) # Prints only columns with missing values

This chain of commands works as follows:

  1. df.isnull(): Returns a DataFrame of the same shape as df, but with True where values are NaN and False otherwise.
  2. .sum(): When applied to this boolean DataFrame, it treats True as 1 and False as 0, effectively summing up the True values for each column.

Strategy 1: Dropping Missing Values

The simplest approach is to remove rows or columns that contain NaN values using the .dropna() method.

  • df.dropna(): This will drop any row that contains at least one NaN value.
  • df.dropna(axis=1): This will drop any column that contains at least one NaN value.

When to use dropna()?

  • When only a small fraction of your rows have missing data, and losing them won't significantly impact your dataset.
  • When a specific column is mostly empty and not critical for your analysis, you can drop the entire column.

Be careful with dropna(). If a key feature has missing values scattered throughout the dataset, you could end up dropping a large portion of your data.

Strategy 2: Imputing Missing Values

A more common and often better approach is imputation, which means filling in the missing values using the .fillna() method.

You can fill NaNs with:

  • A constant value: df['column_name'].fillna(0) or df['category_column'].fillna('Unknown'). This is useful when 0 has a logical meaning (e.g., "0 items sold") or for categorical data.
  • A statistical measure: For numerical data, filling with the mean, median, or mode is very common. The median is generally preferred over the mean because it is less sensitive to outliers.
# Fill missing values in a numerical column with its median
median_value = df['numerical_column'].median()
df['numerical_column'] = df['numerical_column'].fillna(median_value)

You'll often see the inplace=True argument used with methods like fillna(). For example, df['col'].fillna(0, inplace=True). This modifies the DataFrame directly without needing to reassign it. While it can save typing, it's often considered better practice to reassign (df['col'] = ...), as this is more explicit and less prone to errors in complex data pipelines. This is analogous to avoiding functions with side effects in software development.


2. Correcting Data Types

The second major issue you'll spot with .info() is incorrect data types (Dtype). For example, a column of numbers might be loaded as object (which is what Pandas uses for strings) because it contains commas, currency symbols, or was corrupted. You cannot perform mathematical operations on an object column.

The following resources detail how to check and convert data types.

Practical Examples of Data Cleaning Using Pandas and ...

The same article also has a great section on correcting data types. Pay close attention to the pd.to_numeric function, which is particularly robust.

Now read Section 3, 'Correcting Data Types'. Below the heading, review data type correction. Focus on the difference between .astype() and pd.to_numeric.

and

How to Use Pandas for Data Cleaning and Preprocessing

This article from freeCodeCamp provides another clear perspective on why data types are important and how to convert them.

Read the section 'Data Types and Conversion'. Explore the conversion process, which provides a concise explanation of astype() and how to check types with .dtypes.

Identifying Data Types

As you know from the last lesson, you can see all column types at once with df.info(). To check types programmatically, you can use the .dtypes attribute:

print(df.dtypes)

Conversion Methods

  1. .astype(): This is the most straightforward method. You can use it to cast a column to a different type.

    # Convert 'price' column from object to float
    df['price'] = df['price'].astype(float)
    
    # Convert 'user_id' from float to integer
    df['user_id'] = df['user_id'].astype(int)
    

    However, astype() will raise an error if it encounters a value it cannot convert (e.g., a string like 'N/A' in a column you're converting to float).

  2. pd.to_numeric(): This function is more flexible and robust for converting to numerical types. Its most important parameter is errors.

    • errors='raise' (default): Raises an error if a value can't be converted.
    • errors='coerce': This is extremely useful. It will replace any value that cannot be converted with NaN.

    This errors='coerce' behavior creates a powerful two-step cleaning pattern:

    1. Attempt to convert the column to a numeric type, forcing errors into NaN values.
    2. Use the imputation techniques you just learned to fill in those new NaNs.
    # Let's say 'total_sales' contains numbers but also some text like 'Not Available'
    
    # Step 1: Convert to numeric, coercing errors to NaN
    df['total_sales'] = pd.to_numeric(df['total_sales'], errors='coerce')
    
    # Now the 'Not Available' entries are NaN.
    # We can check how many were created: df['total_sales'].isnull().sum()
    
    # Step 2: Fill the new NaNs with the median
    sales_median = df['total_sales'].median()
    df['total_sales'] = df['total_sales'].fillna(sales_median)
    

    This pattern is much like using a try-catch block when parsing data in general-purpose programming—it allows you to handle failures gracefully.

Test your understanding!

You are given a DataFrame df with information about product listings. It has two columns of interest: units_sold (which has some missing values) and rating (which should be numeric from 1-5 but is currently an object type because some entries are 'No Rating').

Write a short Python script using Pandas to:

  1. Fill the missing values in the units_sold column with the column's median.
  2. Convert the rating column to a numeric type. Any 'No Rating' entries should be replaced with 0.
import pandas as pd
import numpy as np

data = {'units_sold': [100, 150, np.nan, 200, 120, np.nan],
        'rating': ['4.5', '3.0', '5.0', 'No Rating', '4.0', 'No Rating']}
df = pd.DataFrame(data)

# Your cleaning code here
Show answer

Here is the solution:

import pandas as pd
import numpy as np

data = {'units_sold': [100, 150, np.nan, 200, 120, np.nan],
        'rating': ['4.5', '3.0', '5.0', 'No Rating', '4.0', 'No Rating']}
df = pd.DataFrame(data)

# 1. Fill missing values in 'units_sold' with the median
median_sold = df['units_sold'].median()
df['units_sold'] = df['units_sold'].fillna(median_sold)

# 2. Convert 'rating' to numeric, handling non-numeric entries
# Use pd.to_numeric with errors='coerce' to turn 'No Rating' into NaN
df['rating'] = pd.to_numeric(df['rating'], errors='coerce')

# Fill the resulting NaNs with 0
df['rating'] = df['rating'].fillna(0)

# You could also chain the methods:
# df['rating'] = pd.to_numeric(df['rating'], errors='coerce').fillna(0)

print(df)
print(df.info())

The output will show a clean DataFrame with no missing values and with both columns having numeric data types (float64 or int64).


Conclusion

In this lesson, you've acquired the fundamental skills for cleaning a dataset in Pandas. This is often one of the most time-consuming but essential parts of any AI project.

Key Takeaways:

  • Always start by identifying issues using .info() and isnull().sum().
  • Handle missing values by either dropping (.dropna()) them when appropriate or imputing (.fillna()) them with a sensible value (like the median for numerical data).
  • Correct data types using .astype() for simple cases or the more robust pd.to_numeric(errors='coerce') for columns with non-numeric characters.
  • The pd.to_numeric + fillna pattern is a powerful combination for cleaning messy numerical columns.

Next up:
Now that your data is clean and in the correct format, the next logical step is to start selecting and filtering it to isolate the specific subsets of data you need for your analysis. In the next lesson, we will dive into the powerful indexing and selection capabilities of Pandas.