Introduction
Empty cells are common in real-world datasets. They may appear when information is missing, not entered, or unavailable. These empty cells can affect calculations and data analysis. Pandas Cleaning Empty Cells provides functions such as dropna() and fillna() to handle missing values. In this chapter, you will learn how to identify, remove, and replace empty cells in a DataFrame.
What Are Empty Cells in Pandas?
Empty cells are values that are missing from a dataset. In Pandas, missing values are commonly represented as NaN (Not a Number) or None.
Example:
import pandas as pd
data = {
"Name": ["Amit", "Neha", "Rahul", "Priya", "Karan"],
"Age": [25, 28, None, 30, 27],
"Salary": [35000, None, 32000, 45000, None]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age Salary
0 Amit 25.0 35000.0
1 Neha 28.0 NaN
2 Rahul NaN 32000.0
3 Priya 30.0 45000.0
4 Karan 27.0 NaN
Explanation: The Age and Salary columns contain missing values. Pandas displays these missing numerical values as NaN.
Identifying Empty Cells Using isnull()
The isnull() function checks whether each cell contains a missing value.
It returns:
Trueif the cell contains a missing value.Falseif the cell contains a value.
Example:
print(df.isnull())
Output:
Name Age Salary
0 False False False
1 False False True
2 False True False
3 False False False
4 False False True
Explanation: The output shows True wherever a missing value exists. Here, the Salary column has missing values in rows 1 and 4, while the Age column has a missing value in row 2.
Counting Empty Cells Using isnull().sum()
You can use isnull().sum() to count the number of missing values in each column.
Example:
print(df.isnull().sum())
Output:
Name 0
Age 1
Salary 2
dtype: int64
Explanation: The result shows that the Age column has one missing value and the Salary column has two missing values.
Removing Empty Cells 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
0 Amit 25.0 35000.0
3 Priya 30.0 45000.0
Explanation: Rows 1, 2, and 4 are removed because they contain at least one missing value. Only rows with complete data remain.
Note: By default, dropna() removes rows containing missing values and returns a new DataFrame. The original DataFrame remains unchanged.
Removing Empty Cells Using inplace=True
You can use inplace=True to remove missing-value rows directly from the original DataFrame.
Example:
df.dropna(inplace=True)
print(df)
Output:
Name Age Salary
0 Amit 25.0 35000.0
3 Priya 30.0 45000.0
Explanation: The inplace=True parameter modifies the original DataFrame instead of creating a separate DataFrame.
Filling Empty Cells Using fillna()
Instead of deleting rows, you can replace missing values with a specific value using fillna().
Example:
new_df = df.fillna(0)
print(new_df)
Output:
Name Age Salary
0 Amit 25.0 35000.0
1 Neha 28.0 0.0
2 Rahul 0.0 32000.0
3 Priya 30.0 45000.0
4 Karan 27.0 0.0
Explanation: The fillna(0) function replaces every missing value with 0. This is useful when zero is a meaningful replacement for the missing data.
Filling Empty Cells with Different Values
You can fill missing values in different columns with different values by passing a dictionary to fillna().
Example:
new_df = df.fillna({
"Age": 0,
"Salary": 25000
})
print(new_df)
Output:
Name Age Salary
0 Amit 25.0 35000.0
1 Neha 28.0 25000.0
2 Rahul 0.0 32000.0
3 Priya 30.0 45000.0
4 Karan 27.0 25000.0
Explanation:
- Missing values in the
Agecolumn are replaced with0. - Missing values in the
Salarycolumn are replaced with25000.
This approach is useful when different columns require different replacement values.
Filling Empty Cells with the Mean
The mean is the average of numerical values. You can calculate the mean of a column and use it to replace missing values.
Example:
mean_age = df["Age"].mean()
df["Age"] = df["Age"].fillna(mean_age)
print(df)
Output:
Name Age Salary
0 Amit 25.0 35000.0
1 Neha 28.0 NaN
2 Rahul 27.5 32000.0
3 Priya 30.0 45000.0
4 Karan 27.0 NaN
Explanation:
df["Age"].mean()calculates the average of the available Age values.- The average is
(25 + 28 + 30 + 27) / 4 = 27.5. fillna(mean_age)replaces the missing Age value with27.5.
Note: The mean is useful for numerical data when it is a suitable representation of the missing values.
Filling Empty Cells with the Median
The median is the middle value of a sorted dataset. It can be used to fill missing numerical values, especially when the data contains unusually high or low values.
Example:
median_salary = df["Salary"].median()
df["Salary"] = df["Salary"].fillna(median_salary)
print(df)
Output:
Name Age Salary
0 Amit 25.0 35000.0
1 Neha 28.0 40000.0
2 Rahul 27.5 32000.0
3 Priya 30.0 45000.0
4 Karan 27.0 40000.0
Explanation:
df["Salary"].median()calculates the median of the available salary values.- The median is
40000. fillna(median_salary)replaces missing salary values with40000.
Filling Empty Cells with the Mode
The mode is the most frequently occurring value in a dataset. It is commonly used to fill missing values in categorical columns.
Example:
data = {
"Name": ["Amit", "Neha", "Rahul", "Priya", "Karan"],
"Department": ["IT", "HR", None, "IT", "IT"]
}
df = pd.DataFrame(data)
department_mode = df["Department"].mode()[0]
df["Department"] = df["Department"].fillna(department_mode)
print(df)
Output:
Name Department
0 Amit IT
1 Neha HR
2 Rahul IT
3 Priya IT
4 Karan IT
Explanation:
mode()finds the most frequently occurring department.mode()[0]selects the first mode value.fillna(department_mode)replaces the missing department withIT.
Student Task
Create a DataFrame named employees using the following data:
| Name | Department | Age | Salary |
|---|---|---|---|
| Amit | IT | 25 | 35000 |
| Neha | HR | 28 | Empty |
| Rahul | Empty | 24 | 32000 |
| Priya | IT | Empty | 45000 |
| Karan | HR | 30 | Empty |
| Simran | Sales | 26 | 38000 |
Your Tasks:
- Create a Pandas DataFrame using the given employee data.
- Identify empty cells using
isnull(). - Count missing values in each column using
isnull().sum(). - Remove rows containing empty cells using
dropna(). - Fill all missing values with
0usingfillna(). - Fill missing Age values with the mean of the Age column.
- Fill missing Salary values with the median of the Salary column.
- Fill the missing Department value with the mode of the Department column.
Key Takeaways
- Empty cells represent missing information in a dataset.
- Pandas commonly represents missing values as
NaNorNone(Pandas Missing Values). isnull()identifies missing values(Pandas Missing Values)isnull().sum()counts missing values in each column.dropna()removes rows containing missing values by default.inplace=Truemodifies the original DataFrame.fillna()replaces missing values with specified values.mean()calculates the average.median()calculates the middle value.mode()finds the most frequently occurring value.
Frequently Asked Questions (FAQs)
1. What Is Pandas Cleaning Empty Cells in Python?
Pandas Cleaning Empty Cells is the process of identifying and handling missing or empty values in a Pandas DataFrame. It helps improve data quality and prepares datasets for accurate analysis.
2. How to Identify Pandas Missing Values in a DataFrame?
You can identify Pandas Missing Values using the isnull() or isna() function. These functions return True for missing values and False for non-missing values.
3. How to Remove Empty Cells in Pandas?
You can Remove Empty Cells in Pandas using the dropna() function. It removes rows or columns containing missing values from a DataFrame.
4. How to Fill Empty Cells in Pandas?
You can Fill Empty Cells in Pandas using the fillna() function. It replaces missing values with a specified value, such as 0, a text value, or another suitable value.
5. What Is the Difference Between dropna() and fillna() in Pandas?
The dropna() function removes rows or columns containing missing values, whereas the fillna() function replaces missing values with specified values. Both functions are useful for handling missing data in Pandas.
6. How to Count Missing Values in Each Column Using Pandas?
You can count missing values in each column using the isnull().sum() expression. It returns the total number of missing values in every DataFrame column.
7. Why Is Handling Missing Values Important in Python Data Cleaning?
Handling missing values is an important part of Python Data Cleaning because incomplete data can affect calculations, statistical results, and data analysis. Removing or filling missing values helps improve dataset quality.
8. Can We Replace Missing Values with the Mean or Median in Pandas?
Yes, you can replace missing values with the mean or median using the fillna() function. This approach is useful when cleaning numerical datasets and preparing data for further analysis.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
