Data Cleaning: Taming Messy Data
7 min read
Welcome to the Data Cleaning section of the freeCodeCamp Pandas course! Think of yourself as a data detective. Your mission, should you choose to accept it, is to take messy, real-world data and transform it into a clean, organized, and reliable source of truth. It might sound like a chore, but with the power of Pandas, it's more like a satisfying puzzle.
Real-world data is rarely perfect. It often has missing values, duplicate entries, and confusing column names. Before you can even think about doing any fancy analysis or building machine learning models, you need to roll up your sleeves and clean it up. It's a crucial first step that can make or break your entire project.
1. Identifying Missing Data: isna() and notna() 🕵️♀️
The Problem: You've just loaded a dataset, and you have a sneaking suspicion that some values are missing. These missing values, often represented as NaN (Not a Number), can cause errors in your calculations and lead to misleading results. How do you find these pesky missing values?
The Solution: Pandas provides two handy functions to detect missing data: isna() and its alias isnull(), and their opposite, notna() and its alias notnull().
isna()/isnull(): These functions return a DataFrame of the same shape as your original DataFrame, but with boolean values.Trueindicates that the value is missing (NaN), andFalseindicates that it's present.notna()/notnull(): As you might guess, these do the exact opposite. They returnTruefor non-missing values andFalsefor missing ones.
Let's see it in action:
Imagine you're managing a database for an intergalactic pet adoption agency.
import pandas as pd
import numpy as np
data = {'Pet_ID': [101, 102, 103, 104],
'Name': ['Zorp', 'Gleeb', np.nan, 'Fluffy'],
'Age': [5, np.nan, 2, 8],
'Planet': ['Mars', 'Venus', 'Mars', np.nan]}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
print("\nIdentifying missing values with isna():")
print(df.isna())
print("\nIdentifying non-missing values with notna():")
print(df.notna())Under the Hood: When you use isna() or notna(), Pandas iterates through each element of your DataFrame and checks if it's a missing value. In Python, missing values can be represented by None or numpy.NaN. These functions are highly optimized to perform this check quickly, even on very large datasets.
2. The Easy Way Out: Dropping Missing Values with dropna() 🗑️
The Problem: Now that you've identified the missing values, what do you do with them? One common approach, especially when you have a large dataset and only a few missing values, is to simply remove the rows or columns that contain them.
The Solution: Pandas gives you the dropna() method to do just that.
Key Parameters:
axis: This parameter determines whether you want to drop rows (axis=0oraxis='index') or columns (axis=1oraxis='columns') that contain missing values. The default is to drop rows.how: This parameter lets you specify whether to drop a row or column if it has 'any' missing values (the default) or if 'all' of its values are missing.subset: If you only want to consider certain columns when looking for missing values, you can pass a list of column names to this parameter.inplace: If you set this toTrue, the original DataFrame will be modified directly. By default,dropna()returns a new DataFrame with the changes.
Example Time:
Let's go back to our alien pet adoption agency.
# Drop rows with any missing values
df_dropped_rows = df.dropna()
print("\nDataFrame after dropping rows with any missing values:")
print(df_dropped_rows)
# Drop columns with any missing values
df_dropped_cols = df.dropna(axis=1)
print("\nDataFrame after dropping columns with any missing values:")
print(df_dropped_cols)
# Drop rows where 'Name' or 'Planet' is missing
df_dropped_subset = df.dropna(subset=['Name', 'Planet'])
print("\nDataFrame after dropping rows where 'Name' or 'Planet' is missing:")
print(df_dropped_subset)Industry Practice: While dropping missing data is a quick fix, be cautious. If a significant portion of your data is missing, this approach can lead to a loss of valuable information. Always consider the potential impact on your analysis before dropping data.
3. Plugging the Holes: Filling Missing Values with fillna() mengisi
The Problem: What if dropping missing values isn't an option? Perhaps you don't have enough data to spare, or the missing values are in a crucial column. In such cases, you need a way to fill in the gaps.
The Solution: The fillna() method in Pandas is your go-to tool for this task. It allows you to replace NaN values with a specified value or using a particular method.
Common Filling Strategies:
- A specific value: You can fill all missing values with a constant, like 0 or the string "Unknown".
- The mean, median, or mode: For numerical data, filling with the mean or median is a common practice. For categorical data, the mode (most frequent value) is often used.
- Forward or backward fill: You can propagate the last valid observation forward (
method='ffill') or the next valid observation backward (method='bfill').
Let's get our hands dirty:
# Fill all missing values with 0
df_filled_zero = df.fillna(0)
print("\nDataFrame after filling missing values with 0:")
print(df_filled_zero)
# Fill 'Age' with the mean age
mean_age = df['Age'].mean()
df_filled_mean = df.copy()
df_filled_mean['Age'] = df_filled_mean['Age'].fillna(mean_age)
print("\nDataFrame after filling missing 'Age' with the mean age:")
print(df_filled_mean)
# Fill 'Planet' with the mode
mode_planet = df['Planet'].mode()[0]
df_filled_mode = df.copy()
df_filled_mode['Planet'] = df_filled_mode['Planet'].fillna(mode_planet)
print("\nDataFrame after filling missing 'Planet' with the mode:")
print(df_filled_mode)
# Forward fill missing values
df_ffill = df.fillna(method='ffill')
print("\nDataFrame after forward filling:")
print(df_ffill)Fun Fact: The term "imputation" is often used in statistics to refer to the process of replacing missing data with substituted values. So, when you're using fillna(), you're performing data imputation!
4. Handling Duplicates: duplicated() and drop_duplicates() 👯
The Problem: Duplicate data can be a real headache. It can skew your analysis, lead to incorrect counts, and generally make your data untrustworthy. Imagine counting the number of unique customers, but some are listed multiple times!
The Solution: Pandas provides two essential methods for dealing with duplicates: duplicated() to identify them and drop_duplicates() to remove them.
duplicated(): This method returns a boolean Series indicating whether each row is a duplicate of a previous one.drop_duplicates(): This method returns a new DataFrame with the duplicate rows removed.
Key Parameters for drop_duplicates():
subset: Specify a list of column names to consider when identifying duplicates. By default, it considers all columns.keep: This determines which duplicate to keep. 'first' (default) keeps the first occurrence, 'last' keeps the last one, andFalsedrops all duplicates.inplace: Similar todropna(), set this toTrueto modify the original DataFrame.
Let's try it out:
Suppose we have some new entries in our pet adoption database, and some of them are duplicates.
data_with_dupes = {'Pet_ID': [101, 102, 101, 103, 104],
'Name': ['Zorp', 'Gleeb', 'Zorp', 'Fluffy', 'Gleeb'],
'Age': [5, 3, 5, 8, 3],
'Planet': ['Mars', 'Venus', 'Mars', 'Earth', 'Venus']}
df_dupes = pd.DataFrame(data_with_dupes)
print("\nOriginal DataFrame with duplicates:")
print(df_dupes)
# Identify duplicate rows
print("\nIdentifying duplicate rows:")
print(df_dupes.duplicated())
# Drop duplicate rows, keeping the first instance
df_no_dupes = df_dupes.drop_duplicates()
print("\nDataFrame after dropping duplicates:")
print(df_no_dupes)
# Drop duplicates based on the 'Name' and 'Planet' columns
df_no_dupes_subset = df_dupes.drop_duplicates(subset=['Name', 'Planet'], keep='last')
print("\nDataFrame after dropping duplicates based on 'Name' and 'Planet', keeping the last instance:")
print(df_no_dupes_subset)5. Renaming Columns and Indices for Clarity 🏷️
The Problem: Column and index names are not always clear or convenient to work with. They might have inconsistent capitalization, spaces, or just be plain uninformative. This can make your code harder to read and write.
The Solution: The rename() method is a powerful tool for changing the names of your columns and indices.
How it works:
You can pass a dictionary to the columns or index parameter of the rename() method. The keys of the dictionary are the old names, and the values are the new names.
Let's rename some things:
# Rename columns
df_renamed = df.rename(columns={'Pet_ID': 'PetID', 'Name': 'PetName'})
print("\nDataFrame with renamed columns:")
print(df_renamed)
# Rename an index
df_indexed = df.set_index('Pet_ID')
df_renamed_index = df_indexed.rename(index={101: 'P101'})
print("\nDataFrame with a renamed index:")
print(df_renamed_index)Pro-Tip: In the industry, it's a common practice to make all column names lowercase and replace spaces with underscores (_) for easier access and to avoid potential issues with certain programming languages or databases.
df.columns = df.columns.str.lower().str.replace(' ', '_')
print("\nDataFrame with standardized column names:")
print(df.columns)This is just a glimpse into the world of data cleaning with Pandas. Mastering these techniques will make you a more effective and efficient data professional. Remember, clean data is the foundation of any great data analysis.
Further Reading & References
- Official Pandas Documentation:
isna(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isna.htmlnotna(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.notna.htmldropna(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.htmlfillna(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.htmlduplicated(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.htmldrop_duplicates(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop_duplicates.htmlrename(): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html
Challenge
You are provided with a raw Pandas DataFrame named df containing user data. This data is messy and requires cleaning. Your task is to perform a series of data cleaning operations in the specified order and store the final, clean data in a new DataFrame called cleaned_df.
Required Cleaning Steps:
Standardize Column Names: Convert all column names to lowercase and replace all spaces with underscores.
Remove Duplicates: Some users have multiple entries. Identify and remove duplicate rows based on the
user_idandemailcolumns. When a duplicate is found, keep only the most recent entry (the last one that appears in the DataFrame).Impute Missing Values: Address the missing data (
NaNvalues) in the following columns using these specific strategies:- In the
agecolumn, fill any missing values with the median of the entire column. - In the
citycolumn, fill any missing values with the most frequently occurring city (the mode). - In the
last_login_datecolumn, propagate the last valid observation forward to fill the gaps.
- In the
Ensure Data Integrity: After the previous steps, remove any rows that still have a missing value in the
user_idcolumn.
Expected result
The final cleaned_df DataFrame should be the result of applying all the cleaning steps to the initial df.
Your final DataFrame should have the following characteristics:
- Shape: It should contain 7 rows and 6 columns.
- Column Names: All column names must be in snake_case (e.g.,
user_id,full_name,last_login_date). - Duplicates: The initial duplicate entries for
user_id101 and 102 should be resolved, keeping only the last occurrence for each. - Missing
user_id: The row that initially had aNaNvalue forUser IDshould be completely removed. - Imputed Values:
- The
agecolumn should have no missing values. The originalNaNs should be replaced by the calculated median age (35.5). - The
citycolumn should be completely filled. The originalNaNvalue should be replaced by the mode, which is'New York'. - The
last_login_datecolumn should have noNaNs. The missing values should be forward-filled, resulting in them being populated with'2023-01-13'.
- The
- Untouched
NaN: TheNaNvalue in theemailcolumn for user 105 should remain, as its cleaning was not specified in the instructions.