Lesson 12: Working with Real Data — Pandas Essentials
Load CSV data into a DataFrame; explore, select, filter, and clean data.
By Bishwambhar Sen • Last updated • 75 min
Real-world data is messy. It's often in CSV files or SQL databases. Pandas is the ultimate tool for wrangling structured data.
Think of Pandas as Excel or Google Sheets, but running on Python code. We usually import it as pd.
The DataFrame
The core of Pandas is the DataFrame — a 2D table of data with rows and columns.
# Usually, you load data from a file:
# df = pd.read_csv("housing.csv")
# You can see the first few rows like this:
df.head()
Interactive DataFrame Explorer
Run typical Pandas commands on real Titanic passenger data and inspect the output.
Notice the missing ages (NaN) inside our dataset. Click below to fill missing records with the column average (30).
| Idx | Name | Pclass | Age | Fare | Survived |
|---|---|---|---|---|---|
| 0 | John Doe | 3 | 22 | $7.25 | 0 |
| 1 | Jane Smith | 1 | 38 | $71.28 | 1 |
| 2 | William Cook | 3 | NaN | $8.05 | 0 |
| 3 | Anna Brown | 1 | 35 | $53.10 | 1 |
| 4 | Charles Case | 3 | 28 | $8.46 | 0 |
| 5 | Emily Stone | 2 | 19 | $26.00 | 1 |
| 6 | Thomas Davis | 3 | NaN | $7.89 | 0 |
| 7 | George Vance | 1 | 54 | $51.86 | 0 |
Exploring Data
Before training a model, you must understand your data.
df.shape- Returns (rows, columns)df.info()- Column names, data types, and missing valuesdf.describe()- Summary statistics (mean, min, max) for numeric columns
Filtering and Selecting
You can grab specific columns (Features) or filter rows based on conditions.
prices = df["Price"]
# Filter rows:
expensive_homes = df[df["Price"] > 500000]
Coding Challenge: Prepping Data
Imagine we have a Pandas DataFrame called df loaded with passenger data from the Titanic. Your job is to prep the features and labels!
- Create a new DataFrame called
featuresby selecting only the columns:["Pclass", "Age", "Fare"]. (Hint: pass a list of strings inside the brackets). - Create a Pandas Series called
labelsby selecting just the"Survived"column. - The dataset has missing ages. Use
features["Age"].fillna(30)to replace missing ages with 30, and assign the result back tofeatures["Age"]. - Print
features.head()to verify your work.