惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
Vercel News
Vercel News
Last Week in AI
Last Week in AI
罗磊的独立博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
美团技术团队
U
Unit 42
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
J
Java Code Geeks
V
V2EX
量子位
腾讯CDC
S
SegmentFault 最新的问题
The GitHub Blog
The GitHub Blog
G
Google Developers Blog
D
DataBreaches.Net
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 聂微东
L
LangChain Blog
C
Check Point Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Pandas for Data Cleaning in Data Science Introduction
Samuel Mwai · 2026-06-15 · via DEV Community

In the field of data science and analytics, raw data is rarely perfect. Real-world datasets often contain missing values, duplicate records, incorrect formats, inconsistent text, and outliers that can affect the accuracy of analysis and machine learning models. Data cleaning is the process of detecting, correcting, and preparing raw data so that it becomes reliable and ready for analysis.

One of the most powerful tools for data cleaning in Python is Pandas. Pandas is an open-source Python library that provides easy-to-use data structures and functions for manipulating and analyzing structured data. With its DataFrame and Series objects, Pandas allows data professionals to efficiently clean datasets of any size.

  1. Loading Data into Pandas

Before cleaning data, the first step is importing it into a Pandas DataFrame.

import pandas as pd

df = pd.read_csv("sales_data.csv")

To inspect the data:

df.head() # Displays first 5 rows
df.tail() # Displays last 5 rows
df.info() # Data types and missing values
df.describe() # Statistical summary
df.shape # Number of rows and columns

Understanding the structure of the dataset helps identify potential data quality issues.

  1. Handling Missing Values

Missing data is one of the most common problems in datasets.

Detecting Missing Values
df.isnull()

Count missing values in each column:

df.isnull().sum()
Removing Missing Values

Remove rows with missing data:

df.dropna()

Remove columns containing missing values:

df.dropna(axis=1)
Filling Missing Values

Replace missing values with a specific value:

df.fillna(0)

Fill numerical data using the mean:

df["Age"] = df["Age"].fillna(df["Age"].mean())

Fill categorical data using the mode:

df["Country"] = df["Country"].fillna(df["Country"].mode()[0])

  1. Removing Duplicate Data

Duplicate records can lead to inaccurate analysis.

Identifying Duplicates
df.duplicated()

Count duplicate rows:

df.duplicated().sum()
Removing Duplicates
df.drop_duplicates()

Remove duplicates based on specific columns:

df.drop_duplicates(subset=["Email"])

  1. Correcting Data Types

Incorrect data types can cause errors during analysis.

Check data types:

df.dtypes
Converting Data Types

Convert a column to an integer:

df["Quantity"] = df["Quantity"].astype(int)

Convert a column to a datetime format:

df["Date"] = pd.to_datetime(df["Date"])

Convert text to a numeric type:

df["Price"] = pd.to_numeric(df["Price"])

  1. Cleaning Text Data

Text data often contains unnecessary spaces, inconsistent capitalization, or formatting problems.

Removing Extra Spaces
df["Name"] = df["Name"].str.strip()
Changing Letter Case

Convert to lowercase:

df["City"] = df["City"].str.lower()

Convert to uppercase:

df["Country"] = df["Country"].str.upper()

Convert to title case:

df["Name"] = df["Name"].str.title()
Replacing Incorrect Values
df["Gender"] = df["Gender"].replace({
"M": "Male",
"F": "Female"
})

  1. Renaming Columns

Column names may be unclear or inconsistent.

Rename a single column:

df.rename(columns={"Cust_Name": "Customer_Name"})

Rename all columns:

df.columns = [
"id",
"name",
"age",
"city"
]

Standardize column names:

df.columns = (
df.columns
.str.strip()
.str.lower()
.str.replace(" ", "_")
)

  1. Filtering Incorrect Data

Sometimes datasets contain impossible or invalid values.

Example: Remove customers with negative ages.

df = df[df["Age"] >= 0]

Remove unrealistic values:

df = df[df["Salary"] <= 500000]

  1. Detecting and Handling Outliers

Outliers are unusual values that significantly differ from the rest of the data.

Using the Interquartile Range (IQR) method:

Q1 = df["Salary"].quantile(0.25)
Q3 = df["Salary"].quantile(0.75)

IQR = Q3 - Q1

lower = Q1 - 1.5 * IQR
upper = Q3 + 1.5 * IQR

df = df[
(df["Salary"] >= lower) &
(df["Salary"] <= upper)
]

  1. Working with Dates

Dates often require cleaning and formatting.

Convert strings to dates:

df["Order_Date"] = pd.to_datetime(df["Order_Date"])

Extract useful information:

df["Year"] = df["Order_Date"].dt.year
df["Month"] = df["Order_Date"].dt.month
df["Day"] = df["Order_Date"].dt.day

  1. Handling Inconsistent Categories

Categories may have different spellings representing the same value.

Example:

Before cleaning:

USA
U.S.A
United States
us

Standardize them:

df["Country"] = df["Country"].replace({
"U.S.A": "USA",
"United States": "USA",
"us": "USA"
})

  1. Finding Unique Values

Checking unique values helps identify inconsistencies.

View unique entries:

df["Country"].unique()

Count each category:

df["Country"].value_counts()

  1. Saving the Cleaned Dataset

After cleaning, save the dataset for future analysis.

Save as CSV:

df.to_csv("cleaned_data.csv", index=False)

Save as Excel:

df.to_excel("cleaned_data.xlsx", index=False)
Best Practices for Data Cleaning with Pandas
Always create a copy of the original dataset before cleaning.
Explore the dataset using head(), info(), and describe().
Handle missing values based on the context of the problem.
Maintain consistent naming conventions.
Validate data after every cleaning step.
Document all transformations to ensure reproducibility.
Use automated cleaning pipelines for large datasets.
Conclusion

Pandas is an essential library for data cleaning in Python and is widely used by data analysts, data scientists, and machine learning engineers. It provides powerful tools for identifying missing values, removing duplicates, correcting data types, standardizing text, handling outliers, and transforming datasets into a usable format.

Effective data cleaning improves the quality of insights, reduces errors in analysis, and creates a strong foundation for advanced tasks such as data visualization, statistical analysis, and machine learning. Mastering Pandas data cleaning techniques is therefore a fundamental skill for anyone pursuing a career in data science and analytics.