Pandas & Data Manipulation — Data Engineering

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="."…

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

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

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"]

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

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.

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

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.

What you will learn