Level 3 In-Depth AI · Programming and Tools
Pandas and Working with Data
Pandas is the standard Python tool for tables of data. Load a CSV, look at it, select and filter rows, summarise groups, join tables and deal with missing values, using the real Titanic passenger list.
- Level
- ●●●●● Beginner
- Reading
- 10 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Python for AIThe full path from zero — 1 concept before this one
- Python for AI
- Pandas and Working with Data
Read them roughly in this order. See it on the concept map →
Why it matters
Before you train any model you have to get the data into shape, and in real projects this takes most of the time. Data arrives as spreadsheets, CSV files, database exports and logs. Columns have odd names, some values are missing, and numbers are stored as text. You need to look at the data, understand it, clean it and turn it into the arrays that a model eats.
Pandas is the Python library for this. It gives you the DataFrame, a table with named columns, much like a spreadsheet you control with code. It is the first tool almost every data scientist opens, whether the data is a customer list, sensor readings, survey answers or the metadata of an image dataset. It feeds directly into scikit-learn and charts, and it is how Data Cleaning and Preparation and Feature Engineering are usually done in practice. Even LLM work involves pandas, for cleaning fine-tuning datasets and analysing evaluation results.
The intuition
A DataFrame is a spreadsheet with three special features:
- Every column has a name and a single type: numbers, text, dates or true/false.
- Every row has a label, called the index. By default it is just 0, 1, 2, … but it can be dates, names or IDs.
- You never edit cells by hand. You write short commands that act on whole columns at once, which makes every step repeatable.
One column on its own is a Series: a labelled list of values of one type. A DataFrame is a set of Series sharing the same index. Under the hood each column is a NumPy array, so everything you learned about vectorised operations applies.
Working with pandas usually means asking questions of the data, one after another. How many rows? What is missing? What was the survival rate? Was it different for women and men? This loop of looking, asking and summarising is called exploratory data analysis. Pandas makes each question a line or two of code.
How it works
We will use a real dataset, the passenger list of the Titanic, which sank in 1912. It has one row per passenger (891 of them in this commonly used version) with whether they survived, their ticket class, sex, age and fare. All outputs below are real.
Loading data
The most common format for tables is CSV (comma-separated values): a plain-text file with one row per line and commas between the columns. pd.read_csv reads one from a file path or a web address:
import pandas as pd
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv"
df = pd.read_csv(url)
df.shape # (891, 15) rows, columns
Pandas also reads Excel (read_excel), JSON (read_json), Parquet (read_parquet, a fast compressed format common in big-data and ML pipelines) and SQL databases. The convention is to call your main table df.
First look
Always start with these:
df.head(3) # first 3 rows (df.tail() for the last ones)
df.info() # column names, types, and how many values are not missing
df.describe() # count, mean, std, min, quartiles and max of numeric columns
df.info() on the Titanic data shows, among other lines:
3 age 714 non-null float64
11 deck 203 non-null str
So 177 passengers have no recorded age and most have no deck. df.describe() reports a mean age of 29.70, a youngest passenger of 0.42 years (a baby of about five months) and a maximum fare of 512.33 pounds against a median of 14.45. That huge gap between median and maximum tells you the fares are very skewed, which matters if you feed them to a model.
Selecting columns and rows
df["age"] # one column -> a Series
df[["sex", "age"]] # a list of columns -> a DataFrame
df.loc[0:2, ["sex", "age"]] # rows by index LABEL, columns by name
df.iloc[:2, :3] # rows and columns by POSITION, like NumPy
The difference between loc and iloc matters. loc uses labels and includes the end of a range, so 0:2 gives three rows. iloc uses positions and, like Python slices, excludes the end.
Filtering
Filtering uses the same boolean mask idea as NumPy. A comparison on a column gives a Series of True/False, and indexing with it keeps the True rows. Combine conditions with & (and) and | (or), with each condition in brackets:
women_3rd = df[(df["sex"] == "female") & (df["pclass"] == 3)]
women_3rd.shape # (144, 15)
df.sort_values("fare", ascending=False).head(3) # the three most expensive tickets
New columns
Arithmetic on columns is vectorised, so creating a feature is one line:
df["family_size"] = df["sibsp"] + df["parch"] + 1 # siblings/spouses + parents/children + self
df["fare_per_person"] = df["fare"] / df["family_size"]
Missing values
Missing entries appear as NaN ("not a number"). Most models cannot handle them, so you must decide what to do. First count them:
df.isna().sum().sort_values(ascending=False).head(4)
# deck 688
# age 177
# embark_town 2
# embarked 2
Then choose, column by column:
- Drop rows:
df.dropna(subset=["age"])keeps the 714 passengers with a known age. Simple, but you lose a fifth of the data, and the rows you lose may not be random. - Fill in a value:
df["age"].fillna(df["age"].median())replaces missing ages with the median, 28. Quick, but it pretends you know something you don't. - Drop the column:
deckis 77% missing and probably not worth rescuing. - Keep the missingness as information:
df["age_missing"] = df["age"].isna(). Whether a value was recorded can itself be predictive.
There is no universally right answer. Data Cleaning and Preparation discusses the trade-offs.
Group, then summarise
The most useful operation in pandas is groupby. It follows a pattern called split–apply–combine: split the rows into groups by the values of one or more columns, apply a summary to each group, and combine the results into a new table.
df["survived"].mean() # 0.384 -> 38.4% survived overall
df.groupby("sex")["survived"].mean()
# female 0.742
# male 0.189
df.groupby(["pclass", "sex"])["survived"].agg(["mean", "count"])
# mean count
# pclass sex
# 1 female 0.97 94
# male 0.37 122
# 2 female 0.92 76
# male 0.16 108
# 3 female 0.50 144
# male 0.14 347
Because survived is 1 for survivors and 0 otherwise, its mean is the survival rate. In three lines you have found the famous pattern: women and first-class passengers were far more likely to survive. value_counts() (how many of each value) and pivot_table (a spreadsheet-style cross table) are close relatives of groupby.
Joining tables
Real data is often spread over several tables that share a key column. A join (pandas calls it merge) combines them by matching that key, just like a database:
ports = pd.DataFrame({"embarked": ["S", "C", "Q"],
"port_country": ["England", "France", "Ireland"]})
df = df.merge(ports, on="embarked", how="left")
how="left" keeps every row of the left table (all 891 passengers) even if no match is found, filling the new columns with NaN. how="inner" keeps only rows that match in both tables. After any join, check the number of rows. If the key is duplicated in the right-hand table, rows multiply.
Handing off to a model
Models want numbers in arrays. df["age"].to_numpy() gives a NumPy array, and pd.get_dummies(df["sex"]) turns a text category into 0/1 columns (one-hot encoding, see Feature Engineering). scikit-learn accepts DataFrames directly.
Key idea Most data work in pandas is a chain of five moves: load, look (
head,info,describe), select and filter, fix (missing values, types, new columns) and summarise (groupby). Always look at the data before modelling it.
In code
A complete first exploration of a real dataset in under 20 lines:
import pandas as pd
url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv"
df = pd.read_csv(url)
print(df.shape)
print(df[["survived", "pclass", "sex", "age", "fare"]].head(3))
print(df.isna().sum().sort_values(ascending=False).head(4))
print(df["survived"].mean().round(3))
print(df.groupby("sex")["survived"].mean().round(3))
df["age"] = df["age"].fillna(df["age"].median()) # fill 177 missing ages
kids = df[df["age"] < 12]
print(len(kids), kids["survived"].mean().round(3))
# (891, 15)
# survived pclass sex age fare
# 0 0 3 male 22.0 7.2500
# 1 1 1 female 38.0 71.2833
# 2 1 3 female 26.0 7.9250
# deck 688
# age 177
# embarked 2
# embark_town 2
# dtype: int64
# 0.384
# sex
# female 0.742
# male 0.189
# Name: survived, dtype: float64
# 68 0.574
The 68 passengers under twelve survived at a rate of 57%, better than adults overall. This needs a network connection to download the file. To work offline, download it once and pass the local path to read_csv instead.
Common pitfalls
- Forgetting that most operations return a new table.
df.dropna()on its own changes nothing. Writedf = df.dropna(). andinstead of&.df[df.age > 10 and df.age < 20]raises an error. Use(df.age > 10) & (df.age < 20), with the brackets.- Chained assignment.
df[df.age < 12]["fare"] = 0tries to modify a temporary copy. Usedf.loc[df.age < 12, "fare"] = 0. Since pandas 3.0 ("copy-on-write"), the chained form never changesdf. - Numbers read as text. A single stray value such as
"n/a"or"1,200"makes pandas read the whole column as text. Checkdf.dtypes, then convert withpd.to_numeric(df[col], errors="coerce"), which turns bad values intoNaN. - Row explosion after a join. Duplicate keys multiply rows. Compare
len(df)before and after every merge. - Slow row-by-row loops.
for i, row in df.iterrows():is very slow on large tables. Use column operations, as with NumPy.
Watch out Filling missing values or scaling columns using statistics of the whole dataset, before splitting off a test set, leaks information from the test data into training and makes results look better than they are. Compute such statistics on the training set only. Training, Validation and Test Sets and scikit-learn pipelines show how.
Where it leads
- Visualising Data turns DataFrames into histograms and scatter plots with one line each.
- scikit-learn trains models directly from DataFrames. Its end-to-end example continues where this chapter stops.
- Data Cleaning and Preparation and Feature Engineering go deeper into cleaning, encoding and creating features.
- For data bigger than memory, the same ideas carry over to faster libraries with similar interfaces, such as Polars, and to SQL. Data Pipelines and Datasets covers data at scale.
A bit of history
Wes McKinney started pandas in 2008 while working at the investment firm AQR Capital, because he needed better tools for financial data analysis in Python. It was open-sourced in 2009. The name comes from "panel data", an economics term for multi-dimensional data over time. The DataFrame idea itself was borrowed from the R language, which had its data.frame for statistics long before. McKinney's book Python for Data Analysis (first edition 2012) helped make pandas, and Python, the standard for data science. Pandas 1.0 arrived only in 2020. Pandas 3.0 brought copy-on-write behaviour and a dedicated text type as defaults.
The Titanic dataset became a teaching favourite largely through Kaggle, whose "Titanic: Machine Learning from Disaster" competition has been the first project for a very large number of beginners.
Try it
- Using
groupby, find the survival rate for each value ofembark_town. Which port's passengers survived most often? Then group by bothembark_townandpclass. Does the class mix explain the difference?- Create a column
is_childthat isTruefor ages under 16, and compute survival rates byis_childandsextogether.- Compare the mean age when you drop missing ages with the mean age after filling them with the median. Why does filling shrink the standard deviation?
Hint for 1:
df.groupby(["embark_town", "pclass"])["survived"].agg(["mean", "count"]).
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
10 Minutes to pandas
The official quick tour of DataFrames.
Kaggle Learn: Pandas
Short hands-on lessons on creating, indexing, grouping and combining DataFrames, with exercises in the browser.
Python for Data Analysis, 3rd edition
The book by pandas' creator on data wrangling with pandas and NumPy. The full text is free to read online.
Python Data Science Handbook
Free online book covering IPython and notebooks, NumPy, pandas, Matplotlib and scikit-learn, every chapter a runnable notebook.
pandas User Guide
The official in-depth guide to indexing, missing data, groupby, merging, reshaping and time series.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/pandas.md