◆ AI All-in-One

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 →
↗ Plan a path here

Read first

Python for AI

This leads to

Data Cleaning and Preparationscikit-learn
The full path from zero — 1 concept before this one
  1. Python for AI
  2. 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.

survived int64 pclass int64 sex str age float64 fare float64 0 0 3 male 22.0 7.25 1 1 1 female 38.0 71.28 2 1 3 female 26.0 7.93 5 0 3 male NaN 8.46 columns: one name, one type each dtype → index row labels df["age"] one column is a Series: a labelled NumPy array NaN = missing value 177 of 891 ages missing ... 891 rows × 15 columns in total
Fig. 1 The anatomy of a DataFrame, using four rows of the Titanic passenger list (row 5 is included because its age is missing). Columns have names and types, rows have an index, one column is a Series, and missing values show up as NaN.

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: deck is 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.

1. Split 2. Apply: mean() 3. Combine sex survived male 0 female 1 female 1 female 1 male 0 male 0 … … 891 passengers female 314 passengers mean of survived = 0.742 male 577 passengers mean of survived = 0.189 sex survived female 0.742 male 0.189 df.groupby("sex")["survived"].mean()
Fig. 2 Split, apply, combine. groupby("sex") splits the 891 passengers into two groups, the mean of the survived column (0 or 1) is computed in each, and the results are combined into a small table. These are the real Titanic numbers.
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. Write df = df.dropna().
  • and instead 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"] = 0 tries to modify a temporary copy. Use df.loc[df.age < 12, "fare"] = 0. Since pandas 3.0 ("copy-on-write"), the chained form never changes df.
  • Numbers read as text. A single stray value such as "n/a" or "1,200" makes pandas read the whole column as text. Check df.dtypes, then convert with pd.to_numeric(df[col], errors="coerce"), which turns bad values into NaN.
  • 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

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

  1. Using groupby, find the survival rate for each value of embark_town. Which port's passengers survived most often? Then group by both embark_town and pclass. Does the class mix explain the difference?
  2. Create a column is_child that is True for ages under 16, and compute survival rates by is_child and sex together.
  3. 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"]).

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You run df.dropna() on its own line, then check df.isna().sum(), and the missing values are all still there. Why?

  2. survived is 1 for survivors and 0 otherwise. What does df.groupby("sex")["survived"].mean() give you?

  3. After df = df.merge(other, on="customer_id", how="left"), your 1,000-row table has 1,400 rows. What most likely happened?

  4. A numeric column comes in as text because a few cells contain "n/a". What is a good fix?

  5. You fill missing ages with the median of the whole dataset, then split off a test set. What is the problem?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Kaggle Learn: Pandas

Kaggle · Beginner · Free

Short hands-on lessons on creating, indexing, grouping and combining DataFrames, with exercises in the browser.

Book

Python for Data Analysis, 3rd edition

Wes McKinney · 2022 · Beginner · free online, print paid

The book by pandas' creator on data wrangling with pandas and NumPy. The full text is free to read online.

Book

Python Data Science Handbook

Jake VanderPlas · 2016 · Beginner · Free

Free online book covering IPython and notebooks, NumPy, pandas, Matplotlib and scikit-learn, every chapter a runnable notebook.

Docs

pandas User Guide

pandas · Intermediate · Free

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