Introduction
Real-world datasets sometimes contain incorrect values that do not follow the expected rules. For example, an employee’s age may be entered as 250 instead of 25, or a product price may contain an incorrect value. Pandas provides functions and techniques to identify and correct these problems. In this chapter, you will learn how to clean wrong data in Pandas. Pandas Cleaning Wrong Data help to understand the concepts of cleaning.
What is Wrong Data in Pandas?
Wrong data means values that are incorrect, unrealistic, or do not match the expected information in a dataset.
For example:
| Name | Age | Salary | Department |
|---|---|---|---|
| Amit | 25 | 35000 | IT |
| Neha | 280 | 40000 | HR |
| Rahul | 24 | -32000 | Sales |
| Priya | 27 | 45000 | IT |
| Karan | 500 | 50000 | HR |
In this dataset:
- Neha’s age is incorrect because 280 is not a realistic employee age.
- Rahul’s salary is incorrect because salary should not be negative in this example.
- Karan’s age is incorrect because 500 is not a realistic employee age.
These values need to be corrected before performing data analysis.
Creating a DataFrame with Wrong Data
Let’s create a DataFrame containing some incorrect values.
Example:
import pandas as pd
data = {
"Name": ["Amit", "Neha", "Rahul", "Priya", "Karan"],
"Age": [25, 280, 24, 27, 500],
"Salary": [35000, 40000, -32000, 45000, 50000]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age Salary
0 Amit 25 35000
1 Neha 280 40000
2 Rahul 24 -32000
3 Priya 27 45000
4 Karan 500 50000
Explanation: The DataFrame contains incorrect Age and Salary values. We will identify these values and correct them using Pandas.
Identifying Wrong Data Using Conditions
You can use comparison operators to identify values that do not follow expected rules.
For example, if employee ages should be between 18 and 60, you can check which records fall outside this range.
Example:
print(df[df["Age"] > 60])
Output:
Name Age Salary
1 Neha 280 40000
4 Karan 500 50000
Explanation: The condition df["Age"] > 60 identifies employees whose age is greater than 60.
Replacing Wrong Data with a Correct Value
If you know the correct value, you can directly update it using the DataFrame’s index.
Example:
df.loc[1, "Age"] = 28
print(df)
Output:
Name Age Salary
0 Amit 25 35000
1 Neha 28 40000
2 Rahul 24 -32000
3 Priya 27 45000
4 Karan 500 50000
Explanation:
loc[1, "Age"]selects the Age value in row 1.= 28replaces the incorrect value 280 with 28.
Replacing Wrong Data Using Conditions
You can also use conditions to replace incorrect values without selecting each row manually.
Suppose employee ages should not be greater than 60. You can replace all ages above 60 with 30.
Example:
df.loc[df["Age"] > 60, "Age"] = 30
print(df)
Output:
Name Age Salary
0 Amit 25 35000
1 Neha 28 40000
2 Rahul 24 -32000
3 Priya 27 45000
4 Karan 30 50000
Explanation: The condition identifies all Age values greater than 60 and replaces them with 30.
Note: The replacement value should be selected based on reliable information. In real projects, do not automatically replace every incorrect value with an arbitrary number.
Removing Rows Containing Wrong Data
Sometimes, you may not know the correct value. In that situation, you can remove the row containing the incorrect data.
For example, suppose negative salaries are not allowed in your dataset.
Example:
df = df[df["Salary"] >= 0]
print(df)
Output:
Name Age Salary
0 Amit 25 35000
1 Neha 28 40000
3 Priya 27 45000
4 Karan 30 50000
Explanation: The condition df["Salary"] >= 0 keeps only rows where the salary is zero or positive. Rahul’s record is removed because the salary is negative.
Replacing Wrong Values Using replace()
The replace() function allows you to replace specific incorrect values with correct values.
Example:
data = {
"Name": ["Amit", "Neha", "Rahul", "Priya"],
"Department": ["IT", "HRA", "Sales", "IT"]
}
df = pd.DataFrame(data)
df["Department"] = df["Department"].replace("HRA", "HR")
print(df)
Output:
Name Department
0 Amit IT
1 Neha HR
2 Rahul Sales
3 Priya IT
Explanation: The replace() function changes the incorrect department name "HRA" to "HR".
Replacing Multiple Wrong Values
You can replace multiple incorrect values in a column by passing a dictionary to replace().
Example:
data = {
"Name": ["Amit", "Neha", "Rahul", "Priya"],
"Department": ["IT Dept", "HRA", "Sales Dept", "HR"]
}
df = pd.DataFrame(data)
df["Department"] = df["Department"].replace({
"IT Dept": "IT",
"HRA": "HR",
"Sales Dept": "Sales"
})
print(df)
Output:
Name Department
0 Amit IT
1 Neha HR
2 Rahul Sales
3 Priya HR
Explanation: The dictionary contains multiple incorrect values and their correct replacements. Pandas updates all matching values in the Department column.
Setting a Range of Values Using Conditions
You can identify values outside an acceptable range and replace them with another value.
For example, suppose product ratings must be between 1 and 5. Any rating outside this range is considered incorrect.
Example:
data = {
"Product": ["Laptop", "Mouse", "Keyboard", "Monitor"],
"Rating": [4, 8, 3, 10]
}
df = pd.DataFrame(data)
df.loc[df["Rating"] > 5, "Rating"] = 5
print(df)
Output:
Product Rating
0 Laptop 4
1 Mouse 5
2 Keyboard 3
3 Monitor 5
Explanation: The condition identifies ratings greater than 5 and replaces them with 5.
Note: This example assumes ratings above 5 should be capped at 5. In an actual dataset, verify the correct rating before changing it.
Student Task
Create a DataFrame named products using the following data:
| Product | Price | Rating | Category |
|---|---|---|---|
| Laptop | 55000 | 4 | Electronics |
| Mouse | -800 | 8 | Accessories |
| Keyboard | 1500 | 5 | Accesories |
| Monitor | 12000 | 10 | Electronics |
| Printer | 9000 | 4 | Electornics |
Your Tasks:
- Create a Pandas DataFrame using the given product data.
- Identify products with a negative price.
- Replace the Mouse price with 800.
- Identify ratings greater than 5.
- Replace ratings greater than 5 with 5.
- Correct
"Accesories"to"Accessories"usingreplace(). - Correct
"Electornics"to"Electronics"usingreplace(). - Display the final cleaned DataFrame.
Key Takeaways
- Wrong data contains incorrect, unrealistic, or inconsistent values.
- Comparison operators help identify incorrect values.
loc[]allows you to update specific rows and columns.- Conditions can identify and replace multiple incorrect values.
- Boolean filtering can remove rows containing unwanted values.
replace()changes specific incorrect values.- A dictionary can be used to replace multiple values.
- Always verify the correct replacement values before cleaning a dataset.
Frequently Asked Questions (FAQs)
1. What Is Pandas Cleaning Wrong Data in Python?
Pandas Cleaning Wrong Data is the process of identifying and correcting incorrect, inconsistent, or inaccurate values in a Pandas DataFrame. It helps make datasets more reliable and suitable for data analysis.
2. How to Fix Wrong Data in Pandas?
You can fix Wrong Data in Pandas using functions such as replace(), loc[], and other DataFrame operations. These methods help correct incorrect values, update records, and make data more consistent.
3. What Is the Use of Pandas replace() Function?
The Pandas replace() function is used to replace specific values in a DataFrame or Series with new values. It is useful for correcting incorrect entries, changing unwanted values, and cleaning datasets.
4. How to Replace Incorrect Values in Pandas DataFrame?
You can replace incorrect values in a Pandas DataFrame using the replace() function. For example, you can replace an incorrect city name, spelling mistake, or unwanted value with the correct value.
5. Why Is Pandas Data Cleaning Important for Data Analysis?
Pandas Data Cleaning is important because incorrect values can lead to inaccurate calculations, misleading reports, and unreliable analysis. Cleaning data helps improve data quality before performing further analysis.
6. How to Replace Multiple Wrong Values Using Pandas?
You can replace multiple wrong values using the Pandas replace() function by passing a dictionary containing the incorrect values and their corresponding correct values.
df["City"] = df["City"].replace({
"Delhii": "Delhi",
"Mumbay": "Mumbai"
})
7. Can Pandas replace() Correct Spelling Mistakes in Data?
Yes, the Pandas replace() function can correct spelling mistakes in categorical data, such as city names, product names, department names, or customer details, by replacing incorrect values with their correct versions.
8. What Are the Common Methods for Cleaning Wrong Data in Pandas?
Common methods for Cleaning Wrong Data in Pandas include using replace() to correct values, loc[] to update specific records, and DataFrame operations to identify and fix inaccurate or inconsistent data.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
