Every morning you open the sales spreadsheet, then sort, filter, remove duplicates and add up. The next day there's more data, and every one of those clicks has to be done again. With pandas, each click becomes one line of code, so tomorrow all the steps just run again. pandas is a Python library for working with tables in memory. Its table is called a DataFrame: rows and columns, where each column has one type. A single column is called a Series.
A first DataFrame from CSV
We use order_lines.csv from the previous lesson: Bookshop's 19 order lines, with their three dirty rows. All output here is from pandas 3.0.6 (the latest release at the time of writing), installed with pip install pandas in a virtual environment.
import pandas as pd
df = pd.read_csv("order_lines.csv", parse_dates=["created_at"])
print(df.shape)
print(df.dtypes)
(19, 9)
item_id int64
order_id int64
created_at datetime64[us]
customer str
city str
book_id int64
title str
qty int64
price int64
dtype: object
import pandas as pdloads the library under the short namepd.pd.read_csv(...)reads the file into a DataFrame and stores it in the variabledf.parse_dates=["created_at"](a list, written in square brackets) tells it to read that column as dates.df.shapeis (rows, columns): 19 rows, 9 columns.df.dtypesis each column's type:int64whole numbers,datetime64[us]dates,strtext. In pandas 3.0 text has its ownstrtype; older versions wrote it asobject.
The types above are pandas' guesses from the contents. You can state them yourself with dtype={"price": "int64"} (a dict: name and value pairs in curly braces). The result for a file whose prices are $18.00: ValueError: invalid literal for int() with base 10: '$18.00'. Good, the error shows. But for a file from a country that writes one thousand as 1.000, even int64 doesn't help: pandas reads it as 1. What helps is thousands=".", which says the dot is a thousands separator.
Cleaning the three dirty rows
print(df["city"].isna().sum())
print(df[df.duplicated(subset=["order_id", "book_id"], keep=False)][["item_id", "order_id", "book_id", "qty"]])
df = df.drop_duplicates(subset=["order_id", "book_id"])
df["city"] = df["city"].fillna("Unknown")
2
item_id order_id book_id qty
7 8 6 2 2
8 9 6 2 2
df["city"]takes one column (a Series)..isna()saysTruefor each empty value, and.sum()counts theTrues: 2, Maya's orders.df.duplicated(subset=[...], keep=False)marks rows whoseorder_idandbook_idare twins.df[...]with those marks filters the rows: items 8 and 9. The leftmost numbers (7 and 8) are the index, pandas' own row numbers.drop_duplicates(...)throws away the twin and keeps the first: 18 rows. The result is stored back indf.fillna("Unknown")replaces empty values. The result is written back to its column withdf["city"] = ....
merge: the catalogue price
The 190 price is fixed by taking the price from books.csv (columns book_id, title, author, catalog_price):
books = pd.read_csv("books.csv")
df = df.merge(books[["book_id", "catalog_price"]], on="book_id", how="left")
df["total"] = df["qty"] * df["catalog_price"]
mergeis pandas'JOIN.on="book_id"is the key column,how="left"means every row ofdfis kept (like aLEFT JOIN).df.merge(books, ...)is the same aspd.merge(df, books, ...).books[["book_id", "catalog_price"]]takes only two columns, sotitledoesn't show up twice.- An operation on a column applies to every row at once:
df["qty"] * df["catalog_price"]multiplies 18 pairs of numbers in one line of code.
Don't mix it up with concat (stacking two tables top to bottom or side by side, without matching keys) and join (combining by index). append was removed in pandas 2.0.
groupby: pandas' GROUP BY
print(df.groupby("city").agg(sold=("qty", "sum"), revenue=("total", "sum")))
sold revenue
city
Bristol 5 110
London 9 192
Manchester 5 99
Unknown 2 43
groupby("city") splits the rows per city, and .agg(name=("column", "function")) works out each group. The total is 21 books and $444, matching the SQL result in the first lesson.
Now run df.groupby("city")["qty"].sum() before cleaning. The data holds 23 books. If you add up its per-city results again, what's the total: 23, 21, or an error? Guess first:
city
Bristol 5
London 11
Manchester 5
Name: qty, dtype: int64
5 + 11 + 5 = 21, while the data holds 23 books. No error, and Maya's 2 books are gone. Unlike SQL, which makes one NULL group, groupby in pandas drops rows whose key is empty. Use fillna first, or groupby("city", dropna=False) so a NaN group shows up.
The owner's question, best seller per city per week:
df["week"] = df["created_at"].dt.to_period("W").dt.start_time
per_title = df.groupby(["week", "city", "title"], as_index=False).agg(sold=("qty", "sum"))
best_sellers = (
per_title.sort_values(["week", "city", "sold", "title"], ascending=[True, True, False, True])
.groupby(["week", "city"])
.head(1)
)
print(best_sellers.to_string(index=False))
week city title sold
2026-09-28 Bristol This Earth of Mankind 2
2026-09-28 London The Rainbow Troops 3
2026-09-28 Manchester Beauty Is a Wound 2
2026-09-28 Unknown The Rainbow Troops 1
2026-10-05 Bristol The Dancer 2
2026-10-05 London Beauty Is a Wound 2
2026-10-05 Manchester The Dancer 1
2026-10-05 Unknown This Earth of Mankind 1
.dt.to_period("W").dt.start_timerounds each date down to the Monday of its week (week;"W"in pandas means a week ending on Sunday).sort_valuessorts: most books sold first in each city, the title as a tie-breaker..groupby([...]).head(1)takes the first row of each week and city.- Manchester in the week of 5 October is actually a tie: The Dancer 1, The Rainbow Troops 1.
head(1)shows only one, so the tie is hidden. The next SQL lesson handles it withRANK().
Copy-on-Write in pandas 3.0
In pandas 3.0, Copy-on-Write is the only mode: every filtered result or selected column behaves like a copy. So code that filters and then assigns in two steps never changes df:
df[df["city"].isna()]["city"] = "Unknown"
pandas 3.0.6 warns ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through chained assignment., and df still has 2 empty cities. df["city"].fillna("Unknown", inplace=True) doesn't change anything either. Write it in one step: df.loc[df["city"].isna(), "city"] = "Unknown", or df["city"] = df["city"].fillna(...) as above. The SettingWithCopyWarning you often saw in pandas 1 and 2 has been removed.
💡 When Polars or DuckDB fits better
pandas loads the whole table into memory and mostly works on one CPU core. For thousands to a few million rows that's fine.
- Polars: a DataFrame library written in Rust that uses every core and has a lazy mode that optimises all the steps before running them. Pick it when pandas gets slow on millions of rows and you want to keep the DataFrame style.
- DuckDB: SQL straight on CSV and Parquet files, even on pandas DataFrames, and it can process data bigger than RAM. Pick it when the work is
GROUP BYandJOIN, especially if the team is more fluent in SQL. For example, on the uncleaneddf:duckdb.sql("SELECT COALESCE(city, 'Unknown') AS city, SUM(qty) AS sold FROM (SELECT DISTINCT order_id, book_id, city, qty FROM df) GROUP BY 1 ORDER BY 1")gives Bristol 5, London 9, Manchester 5, Unknown 2.
Edit in Playground on the Lab opens the SQL version of its pandas code, because this lesson's Playground runs SQL.
⚠️ When pandas quietly gets the numbers wrong
groupbydrops empty keys. ANaNcity disappears without an error.fillnafirst, ordropna=False.1.000becomes 1. Even withdtype={"price": "int64"}. Usethousands=".".- Assigning through chained square brackets.
df[...]["city"] = ...andinplace=Trueon one column don't changedfin pandas 3.0. Use.locor write the column back. head(1)hides ties. When two titles are both the best seller, one of them disappears.
TL;DR: pandas works on tables (DataFrames) in memory with Python. read_csv reads a file; state the types with dtype and the thousands separator with thousands=".", because 1.000 is read as 1. Clean with drop_duplicates(subset=["order_id", "book_id"]), fillna("Unknown"), and the catalogue price through merge(..., on="book_id", how="left"), pandas' JOIN. groupby(...).agg(...) is GROUP BY, but it drops empty keys: before cleaning the total is 21, not 23. In pandas 3.0 Copy-on-Write applies, so df[...]["column"] = ... never changes df; use .loc. For millions of rows or very SQL-shaped work, Polars or DuckDB fits better.
⚡ A DataFrame from CSV
Write:
import pandas as pd
df = pd.read_csv("order_lines.csv", parse_dates=["created_at"])
print(df.shape)
Meaning: A table in pandas is called a DataFrame: rows and columns, each column with one type. A single column is called a Series. df.shape here is (19, 9): 19 rows, 9 columns.
⚡ Clean two dirty rows
Write:
df = df.drop_duplicates(subset=["order_id", "book_id"])
df["city"] = df["city"].fillna("Unknown")
Meaning: drop_duplicates throws away the twin row and keeps the first: 18 rows. fillna fills in the empty cities. The result is written back to df.
⚡ groupby drops empty keys
Guess first: before cleaning, the data holds 23 books. Add up df.groupby("city")["qty"].sum() again. What's the total?
It's 21. No error, but Maya's 2 books are gone: groupby drops rows whose city is empty. Use fillna first, or dropna=False.
Meaning: SQL makes one NULL group; pandas quietly drops it.
⚡ Copy-on-Write
Guess first: df[df["city"].isna()]["city"] = "Unknown". Do the empty cities in df get filled?
No. In pandas 3.0, df[...] is a copy, so only the copy gets filled. Write it in one step: df.loc[df["city"].isna(), "city"] = "Unknown".
Meaning: Assigning through chained square brackets never changes df.