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

推荐订阅源

T
The Exploit Database - CXSecurity.com
F
Fortinet All Blogs
U
Unit 42
F
Full Disclosure
雷峰网
雷峰网
博客园 - 司徒正美
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
罗磊的独立博客
D
DataBreaches.Net
C
Check Point Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
O
OpenAI News
C
CXSECURITY Database RSS Feed - CXSecurity.com
aimingoo的专栏
aimingoo的专栏
S
Security @ Cisco Blogs
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Hacker News
The Hacker News
Webroot Blog
Webroot Blog
Security Latest
Security Latest
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News | PayPal Newsroom
P
Proofpoint News Feed
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
Google Online Security Blog
Google Online Security Blog
H
Help Net Security
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
M
MIT News - Artificial intelligence
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
MyScale Blog
MyScale Blog
腾讯CDC

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Pandas for Data Cleaning: A Practical Guide for Beginners
joseph mwangi · 2026-06-15 · via DEV Community

If you've just started your journey in data analytics, this guide walks you through how to use Pandas, Python's most popular data manipulation library, to clean real-world datasets. Every example here comes from projects I've actually worked on, including a Kenyan hospital operations dataset and a Nairobi housing statistics dataset.

What is Pandas?

Pandas is an open-source Python library built for data manipulation and analysis. Think of it as a supercharged Excel, but inside Python; you can load, filter, clean, transform, and summarize data all in code.
It gives you two core data structures:

  • Series a single column of data:
import pandas as pd

ages = pd.Series([23, 25, 30, 28])
print(ages)

  • DataFrame a full table with rows and columns:
students = {
    "Name": ["Brian", "Caren", "Daisy"],
    "Course": ["Data Analytics", "Data Engineering", "Data Science"],
    "Age": [20, 23, 24]
}

df = pd.DataFrame(students)
df

In real projects, you'll almost always be working with DataFrames.

1. Loading Your Data

The first step in any project is getting your data into Pandas.

From a CSV file

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

From an Excel file (single or multiple sheets)

# Single sheet
df = pd.read_excel("hospital_data.xlsx")

# Specific sheet by name
df = pd.read_excel("hospital_operations_powerbi_sql_dataset.xlsx", sheet_name="Patients")

Loading multiple sheets at once

In my hospital operations project, I needed to load nine sheets from a single Excel workbook. Instead of repeating read_excel nine times, I used a loop:

import pandas as pd

patients     = pd.read_excel("hospital_operations_powerbi_sql_dataset.xlsx", sheet_name="Patients")
doctors      = pd.read_excel("hospital_operations_powerbi_sql_dataset.xlsx", sheet_name="Doctors")
appointments = pd.read_excel("hospital_operations_powerbi_sql_dataset.xlsx", sheet_name="Appointments")
billing      = pd.read_excel("hospital_operations_powerbi_sql_dataset.xlsx", sheet_name="Billing")
# ... and so on

Then I exported all of them to CSV in one go:

csv_tables = {
    "patients": patients,
    "doctors": doctors,
    "appointments": appointments,
    "billing": billing,
    # add the rest...
}

for name, data in csv_tables.items():
    data.to_csv(f"{name}.csv", index=False)

From JSON or SQL

# JSON
df = pd.read_json("data.json")

# SQL (using SQLAlchemy)
from sqlalchemy import create_engine

engine = create_engine("postgresql+psycopg2://username:password@host:port/dbname")
df = pd.read_sql("SELECT * FROM patients", con=engine)

2. Exploring Your Data First

Before cleaning anything, understand what you're working with.

df.head()        # First 5 rows
df.tail()        # Last 5 rows
df.shape         # (rows, columns)
df.columns       # Column names
df.info()        # Data types + null counts
df.describe()    # Summary stats for numbers
df.describe(include='object')  # Summary stats for text columns

Note this df.info() is your best friend when you first open a dataset, it tells you data types AND which columns have missing values at a glance.

3. Handling Missing Values

Missing values are one of the most common data quality problems. Here's how to approach them systematically.

Check what's missing

df.isnull().sum()
# or
df.isna().sum()

Decision guide based on how much is missing

% Missing Recommended Action
< 5% Drop the rows
5% – 40% Fill with median (numbers) or mode (categories)
> 40% Consider dropping the column

To calculate the percentage of missing cells in each row using pandas, use the code


df.isna().mean(axis=1) * 100

Fill missing values

# Numerical-fill with median
df["Age"] = df["Age"].fillna(df["Age"].median())

# Numerical-fill with mean
mean_charge = df["service_charge_kes"].mean()
df["service_charge_kes"] = df["service_charge_kes"].fillna(mean_charge)

# Categorical-fill with a default
df["Gender"] = df["Gender"].fillna("Unknown")

# Fill with zero (e.g., a score that's simply missing)
df["satisfaction_score"] = df["satisfaction_score"].fillna(0)

Drop missing values

# Drop rows where any value is missing
df = df.dropna()

# Drop rows with missing values in specific columns only
df = df.dropna(subset=["service_charge_kes"])
df = df.dropna(subset=["service_charge_kes", "age_of_building_years"])

4. Removing Duplicates

Duplicate records skew your analysis and inflate counts.

# Check how many duplicates exist
df.duplicated().sum()

# Remove them
df = df.drop_duplicates()

In healthcare datasets, duplicate patient records can cause serious reporting errors, so this step is non-negotiable.

5. Fixing Data Types

Pandas sometimes reads columns as the wrong type — for example, dates loaded as strings or numbers loaded as objects.

# Check all data types
df.dtypes

Convert dates

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

If your data has messy or inconsistent date formats, use errors='coerce' to turn bad values into NaT instead of crashing your script:

df["order_date"] = pd.to_datetime(df["order_date"], errors='coerce')

What does errors=['coerce','raise','ignore'] mean?

  • errors='coerce':Invalid values become NaT/NaN (safe)
  • errors='raise': Script stops immediately on bad data (default)
  • errors='ignore':Bad data is left unchanged

Convert multiple date columns at once

date_columns = ["order_date", "delivery_date", "last_login", "subscription_start"]
#what i did here is put 
#the date columns in a list, then
#apply for loop
for col in date_columns:
    df[col] = pd.to_datetime(df[col], errors='coerce')

Convert to numeric

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

6. Cleaning Text Data

Text columns are messy — inconsistent casing, extra spaces, and different formats are all common.

# Standardize casing
df["County"] = df["County"].str.upper()
df["property_type"] = df["property_type"].str.lower()
df["property_type"] = df["property_type"].str.capitalize()

# Remove leading/trailing spaces
df["estate"] = df["estate"].str.strip()

# Replace values
df["Phone"] = df["Phone"].str.replace("254", "0")

# Check if a column contains a keyword
df[df["estate"].str.contains("Kasarani")]

7. Renaming Columns

Clean, consistent column names make your code easier to read.

df = df.rename(columns={
    "Full Name": "full_name",
    "Patient ID": "patient_id",
    "Phone Number": "phone_number"
})

8. Filtering Data

Pandas makes it easy to slice and dice your data to focus on what matters.

Selecting columns

# One column
estates = df["estate"]

# Multiple columns
subset = df[["distance_to_cbd_km", "age_of_building_years", "security_rating"]]

Selecting rows with loc and iloc

# loc — by label/index value
df.loc[[30, 50, 70]]            # Specific rows
df.loc[30, "furnishing"]        # Specific cell

# iloc — by integer position
df.iloc[0]                      # First row
df.iloc[[0, 1, 2]]              # First three rows

Filtering by condition

# Single condition
df[df["Age"] > 60]
df[df["County"] == "NAIROBI"]

# Multiple conditions
df[(df["Age"] > 18) & (df["Gender"] == "Female")]
df[df["bedrooms"] > 2]

9. Sorting Data

# Ascending (smallest to largest)
df.sort_values("bedrooms", ascending=True)

# Descending (largest to smallest)
df.sort_values("parking_slots", ascending=False)

10. Working with Dates

Once your dates are properly formatted, you can extract useful features from them.

Extract year, month, and day

df["order_year"]  = df["order_date"].dt.year
df["order_month"] = df["order_date"].dt.month_name()
df["order_day"]   = df["order_date"].dt.day_name()

Extract quarter

df["order_quarter"] = df["order_date"].dt.quarter

Extract from multiple columns at once

date_cols = ["order_date", "delivery_date", "last_login", "subscription_start"]

for col in date_cols:
    df[f"{col}_month"] = df[col].dt.month
    df[f"{col}_day"]   = df[col].dt.day_name()

Calculate days between dates

df["delivery_days"] = (df["delivery_date"] - df["order_date"]).dt.days

11. Aggregating and Grouping Data

After cleaning, you can summarize your data to generate insights.

# Count patients per county
df.groupby("County")["Patient_ID"].count()

# Average age by gender
df.groupby("Gender")["Age"].mean()

# Median rent by furnishing type
df.groupby("furnishing")["monthly_rent_kes"].median()

# Median rent by property type
df.groupby("property_type")["monthly_rent_kes"].median()

# Quick frequency count
df["furnishing"].value_counts()
df["estate"].value_counts()

12. Feature Engineering

Feature engineering is creating new columns from existing data to unlock better insights.

Age categories

df["Age_Group"] = pd.cut(
    df["Age"],
    bins=[0, 18, 35, 60, 100],
    labels=["Child", "Youth", "Adult", "Senior"]
)

Delivery time

df["delivery_days"] = (df["delivery_date"] - df["order_date"]).dt.days

13. Joining / Merging Datasets

Real-world data is rarely in one table. Pandas lets you join datasets like SQL.

students = pd.DataFrame({
    "student_id": [101, 102, 103, 104, 105],
    "student_name": ["Brian", "Caren", "Daisy", "Eric", "Faith"],
    "course": ["Data Analytics", "Data Engineering", "Data Science", "Data Analytics", "Data Engineering"]
})

payments = pd.DataFrame({
    "student_id": [101, 102, 104, 106, 107],
    "amount_paid": [7500, 15000, 7500, 30000, 10500],
    "payment_status": ["Partial", "Partial", "Partial", "Full", "Partial"]
})

# Inner join — only matching records
inner = pd.merge(students, payments, on="student_id", how="inner")

# Left join — all students, matched payments where available
left = pd.merge(students, payments, on="student_id", how="left")

# Right join — all payments, matched students where available
right = pd.merge(students, payments, on="student_id", how="right")

14. Quick Visualization

Pandas integrates directly with Matplotlib for fast plots.

import matplotlib.pyplot as plt

# Bar chart-patients per county
df["County"].value_counts().plot(kind="bar", title="Patients by County")
plt.show()


# Histogram - age distribution
df["Age"].plot(kind="hist", bins=10, title="Age Distribution")
plt.show()

# Line plot-monthly sales
df.groupby("Month")["Sales"].sum().plot(title="Monthly Sales")
plt.show()

Common Python Errors to Know

When you're just starting out, you'll hit these three types of errors:

SyntaxError — Python can't even read your code. Usually a missing colon, bracket, or indentation issue. The script won't run at all.

RuntimeError — Your code is valid Python, but hits an impossible instruction at runtime, like dividing by zero (ZeroDivisionError) or using a variable that doesn't exist (NameError).

LogicalError — The script runs without crashing, but gives the wrong answer because of a flaw in your logic. These are the hardest to spot:

# Intending to get the average of 4 and 6. Expected: 5
average = 4 + 6 / 2  # Returns 7.0, not 5.0 — order of operations!

# Correct way:
average = (4 + 6) / 2  # Returns 5.0

Full Project References

The code in this article is drawn from real datasets I worked with:

  • Hospital Operations Dataset — Patients, MaritalStatus, Sex, NutritionalStatus, and more. View on GitHub
  • Nairobi Housing Statistics Dataset — Property types, estates, rent prices, and features across Nairobi. View on GitHub

Wrapping Up

Data cleaning is the unglamorous but essential foundation of every good data project. Here's a checklist to keep handy:

  • Load and inspect your data (head, info, describe)
  • Check and handle missing values
  • Remove duplicates
  • Fix data types (especially dates)
  • Clean text columns (casing, spaces, formatting)
  • Filter, sort, and aggregate as needed
  • Engineer new features where useful
  • Join datasets when needed

Pandas makes all of this doable in a few lines of code. The more projects you work on, the more intuitive it becomes.

If you found this useful, feel free to drop a comment or connect happy to answer questions as you work through your first Pandas projects.