Pandas Intro
pandas is a Python library for working with tabular data: rows and columns, like a spreadsheet or a database table. It is the tool most data analysts, scientists and engineers reach for first when they need to load a file, clean it up, answer questions about it and hand the result to a chart or a machine-learning model.
The name comes from "panel data", an econometrics term for data observed over time, and it is written in lower case on purpose. The library was started by Wes McKinney in 2008 and is now an open-source project used by millions of people.
What can pandas do?
| Task | Typical pandas tools |
|---|---|
| Load data from CSV, JSON, Excel, SQL, Parquet… | read_csv(), read_json(), read_excel(), read_sql() |
| Look at it quickly | head(), info(), describe() |
| Clean it | dropna(), fillna(), drop_duplicates(), astype() |
| Select and filter | df["col"], loc[], iloc[], boolean masks, query() |
| Summarise | mean(), value_counts(), groupby(), pivot_table() |
| Combine tables | merge(), concat() |
| Handle dates and time series | to_datetime(), .dt, resample(), rolling() |
| Visualise | df.plot() (built on Matplotlib) |
A first taste
Here is a tiny table of sales from a neighbourhood bakery. Don't worry about every detail yet; just notice how little code it takes to build a table and ask questions about it.
import pandas as pd
sales = pd.DataFrame({
"item": ["croissant", "baguette", "muffin", "baguette", "croissant"],
"qty": [12, 7, 9, 5, 15],
"price": [1.8, 2.4, 2.1, 2.4, 1.8],
})
print(sales) item qty price
0 croissant 12 1.8
1 baguette 7 2.4
2 muffin 9 2.1
3 baguette 5 2.4
4 croissant 15 1.8
pandas printed the table with an index on the left (0 to 4) and one column per key of the dictionary. Now let's compute revenue and total it per item:
import pandas as pd
sales = pd.DataFrame({
"item": ["croissant", "baguette", "muffin", "baguette", "croissant"],
"qty": [12, 7, 9, 5, 15],
"price": [1.8, 2.4, 2.1, 2.4, 1.8],
})
sales["revenue"] = sales["qty"] * sales["price"]
print(sales.groupby("item")["revenue"].sum())
print("Total revenue:", round(sales["revenue"].sum(), 2))item
baguette 28.8
croissant 48.6
muffin 18.9
Name: revenue, dtype: float64
Total revenue: 96.3
Two lines did the work: one multiplied two whole columns at once (no loop!), and one grouped the rows by item and added up the revenue in each group. This style, operating on entire columns instead of single values, is called vectorized code, and it is the heart of pandas.
Why not just use lists and loops?
You could store the same data in lists of dictionaries and write loops. pandas wins because:
- Speed: columns are stored as NumPy arrays, so arithmetic runs in fast compiled code.
- Labels: rows and columns have names, so
sales["qty"]is clearer thanrow[1]. - Missing data: empty values (
NaN) are understood and skipped by most calculations. - Batteries included: grouping, joining, reshaping, dates and plotting are one method call away.
Note: pandas is built on top of NumPy, Python's array library. You don't need to know NumPy to start, but you will meet a few NumPy names such as
np.nan(a missing value) along the way.
How this course works
Every example on these pages runs real pandas (version 2.3) right in your browser through Pyodide, so you can edit the code and press Run. The first run downloads pandas, so it can take a few seconds; later runs are quick.
The course follows the classic order: Series and DataFrames, reading data, cleaning, correlations and plotting. Then it continues with the topics you need for real work: selecting with loc/iloc, grouping, merging, reshaping, time series, window functions and method chaining. It ends with exercises and a mini project.
import pandas as pd
import numpy as np
print("pandas version:", pd.__version__)
print("NumPy version:", np.__version__)pandas version: 2.3.3
NumPy version: 2.2.5
Test yourself
What kind of data is pandas mainly designed for?
- Images and audio
- Tabular data with rows and columns
- Real-time 3D graphics
- Web page layout
Which library is pandas built on top of?
- Django
- NumPy
- Flask
- TensorFlow
What does "vectorized" code mean in pandas?
- Code that draws vector graphics
- Operating on whole columns at once instead of looping over single values
- Code that only works with lists
- Code that runs on a GPU