24. pandas fundamentals
Most data arrives as a table: order lines, customer records, house sales. Module 07 read tables with the csv module, one row at a time, as lists of strings. Module 23 computed fast with NumPy arrays, but an array has no column names and holds one type. pandas joins the two ideas. A pandas table has named columns, a type per column and row labels, and it computes on whole columns at NumPy speed. pandas is the standard tool for tabular data in Python. Almost every later module of this course uses it.
This module uses pandas 3. Two of its defaults differ from older tutorials: text columns have the str dtype, and copy-on-write is always on. The lesson explains both.
What you will learn
Section titled “What you will learn”- Build a
Seriesand aDataFrame, and read their index, columns, values and.dtypes. - Read and write CSV, Excel, JSON and Parquet files, with the
read_csvoptions that fix types at load time:parse_dates,dtype,usecolsandna_values. - Inspect a new dataset with
head,info,describe,shapeandvalue_counts. - Select rows and columns with
[],loc,ilocandquery, and filter with&,|,~,isinandbetween. - Sort with
sort_values,sort_indexandnlargest, and add columns with vectorized arithmetic,assignandnp.where. - Explain why vectorized code beats
apply, convert dtypes withastype,pd.to_numericandpd.to_datetime, and save memory with categoricals.
Prerequisites
Section titled “Prerequisites”- 07. Files and data formats: CSV, JSON, paths and
pathlib. - 04. Data structures: lists, dicts and nested records.
- 05. Functions:
lambdaand functions as arguments. - 23. NumPy: arrays, dtypes, boolean masks and vectorization.
- The course datasets in a
data/folder: Get the data. pandas, NumPy, pyarrow and openpyxl come with the course environment.
Concepts
Section titled “Concepts”What pandas is
Section titled “What pandas is”pandas is a library for tables of data. It gives you two main types:
- A Series is one column: a sequence of values with a label for each value.
- A DataFrame is a table: several Series that share the same row labels.
pandas stores each column as a NumPy array or as an Apache Arrow array. Arrow is a standard memory format for columns of data. The pyarrow package provides it. So a calculation on a column runs as one fast compiled loop, as in module 23.
Import pandas as pd. Every pandas page of this course starts with the same setup block. It fixes how pandas prints tables, so the output is at most 100 characters wide, shows up to 12 columns and rounds floats to 3 decimals for display:
import numpy as npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)print(pd.__version__)3.1.1display.precision changes only what you see. pandas keeps the full value in memory.
Series: labeled values
Section titled “Series: labeled values”A Series holds values of one type and an index: one label per value. A label is a name for a row, such as a product id. If you do not give labels, pandas numbers the rows from 0.
prices = pd.Series( [79.99, 249.00, 1299.00], index=["P001", "P002", "P003"], name="unit_price",)print(prices)print(prices["P002"])P001 79.99P002 249.00P003 1299.00Name: unit_price, dtype: float64249.0The left column is the index. The right column holds the values. The last line shows the name of the Series and its dtype (data type). float64 is a 64-bit float, as in NumPy. prices["P002"] looks up a value by its label, like a dict key.
The parts of a Series are attributes:
print(prices.index)print(prices.to_numpy())print(prices.dtype, prices.size)Index(['P001', 'P002', 'P003'], dtype='str')[ 79.99 249. 1299. ]float64 3.to_numpy() returns the values as a NumPy array. The older attribute .values does the same for numbers, but for text columns it returns a pandas array, not a NumPy array. Prefer .to_numpy().
Arithmetic between two Series matches values by label, not by position. This is index alignment:
units = pd.Series([2, 1], index=["P003", "P001"])print(prices * units)P001 79.99P002 NaNP003 2598.00dtype: float64P001 is first in prices and second in units, but pandas pairs the two P001 values. P002 has no partner, so its result is NaN (“not a number”), the marker for a missing value. Alignment protects you from mixing up rows. It also surprises you when two Series have different labels by accident.
DataFrame: a table of Series
Section titled “DataFrame: a table of Series”A DataFrame is a set of columns. Each column is a Series. All columns share one index. You can build a small DataFrame from a dict: each key is a column name, each value is a list of column values.
stores = pd.DataFrame( { "store_id": ["S01", "S02", "S03"], "city": ["Chicago", "Minneapolis", "Detroit"], "size_sqm": [2850, 1950, 1420], })print(stores)print(stores.shape) store_id city size_sqm0 S01 Chicago 28501 S02 Minneapolis 19502 S03 Detroit 1420(3, 3)The numbers 0, 1 and 2 on the left are the index. pandas made a RangeIndex, a compact index for the row numbers 0 to n − 1. .shape is the tuple (rows, columns), as in NumPy.
flowchart LR
I["index<br/>row labels"] --- C1["column store_id<br/>Series, dtype str"]
C1 --- C2["column city<br/>Series, dtype str"]
C2 --- C3["column size_sqm<br/>Series, dtype int64"]
H["columns<br/>column labels"] -.-> C1
H -.-> C2
H -.-> C3
Four attributes describe every DataFrame:
print(stores.index)print(stores.columns)print(stores.dtypes)print(stores.to_numpy())RangeIndex(start=0, stop=3, step=1)Index(['store_id', 'city', 'size_sqm'], dtype='str')store_id strcity strsize_sqm int64dtype: object[['S01' 'Chicago' 2850] ['S02' 'Minneapolis' 1950] ['S03' 'Detroit' 1420]].indexholds the row labels and.columnsholds the column labels. Both areIndexobjects..dtypesgives the dtype of each column. A DataFrame can mix types; each column has one..to_numpy()(or.values) returns all values as one 2-D NumPy array. With mixed columns, the array has theobjectdtype, which stores general Python objects and is slow. Use it rarely.
One column of a DataFrame is a Series:
city = stores["city"]print(type(city).__name__, city.name)print(city.to_list())Series city['Chicago', 'Minneapolis', 'Detroit']dtypes in pandas 3
Section titled “dtypes in pandas 3”The dtype of a column decides what you can do with it and how much memory it needs. These are the dtypes of this module:
| dtype | Holds | Example column | Missing value |
|---|---|---|---|
int64 |
whole numbers | quantity, sqft |
none allowed |
float64 |
decimal numbers | revenue, lot_sqft |
NaN |
bool |
True / False |
a filter result | none allowed |
str |
text | region, product |
NaN |
datetime64[us] |
dates and times | order_date after parsing |
NaT |
category |
a few repeated values | plan, region |
NaN |
Int64 (capital I) |
whole numbers with gaps | visits with blanks |
<NA> |
object |
any Python object | lists, dicts, mixed values | None or NaN |
Three points matter in practice:
- In pandas 3, text loads as the
strdtype. When pyarrow is installed (the course environment has it), it stores text in Arrow arrays, which is faster and smaller than the oldobjectdtype. Without pyarrow, pandas 3 still showsstrbut stores the text as Python strings. Older tutorials showobjectfor text columns; that is pandas 2 behavior. int64cannot hold a missing value. A whole-number column with a blank cell loads asfloat64instead, withNaNin the gap. The nullable integer dtypeInt64keeps whole numbers and marks a gap as<NA>.NaT(“not a time”) is the missing value of a datetime column.
Reading and writing files
Section titled “Reading and writing files”pandas reads a file into a DataFrame with a pd.read_* function and writes one with a df.to_* method. The pattern is the same for every format:
flowchart LR
F1["sales.csv"] -->|"pd.read_csv"| D["DataFrame"]
F2["sales_sample.xlsx"] -->|"pd.read_excel"| D
F3["customers.json"] -->|"pd.read_json<br/>pd.json_normalize"| D
F4["sales_sample.parquet"] -->|"pd.read_parquet"| D
D -->|"to_csv / to_excel<br/>to_json / to_parquet"| O["output/"]
CSV. pd.read_csv(path) reads a CSV file. It finds the header, splits each line and guesses a dtype for each column. Its options fix the guesses at load time:
| Option | Does | Example |
|---|---|---|
usecols |
load only these columns | usecols=["order_date", "revenue"] |
parse_dates |
parse these columns as dates | parse_dates=["order_date"] |
dtype |
force a dtype per column | dtype={"store_id": "category"} |
na_values |
extra text that means “missing” | na_values=["-"] |
index_col |
use a column as the index | index_col="order_id" |
nrows |
read only the first n rows | nrows=1000 |
sales = pd.read_csv( "data/sales.csv", usecols=["order_id", "order_date", "region", "category", "quantity", "revenue"], parse_dates=["order_date"],)print(sales.shape)print(sales.dtypes)(20228, 6)order_id strorder_date datetime64[us]region strcategory strquantity int64revenue float64dtype: objectusecols kept 6 of the 13 columns. parse_dates turned the order_date text into real dates, with the dtype datetime64[us] (dates with microsecond precision). Without it, order_date stays str, and you cannot compute with it.
df.to_csv(path, index=False) writes a CSV. Pass index=False unless the index holds real data: otherwise pandas writes the 0, 1, 2… labels as an extra unnamed first column. Write results to an output/ folder, never into data/:
from pathlib import Path
Path("output").mkdir(exist_ok=True)sales.head(100).to_csv("output/sales_first_100.csv", index=False)back = pd.read_csv("output/sales_first_100.csv")print(back.shape, back["order_date"].dtype)(100, 6) strThe round trip loses the date dtype. A CSV file stores only text, so the reader must parse the dates again. This is the main weakness of CSV.
Excel. pd.read_excel(path, sheet_name=...) reads one sheet of an .xlsx workbook. pandas uses the openpyxl package to read and write .xlsx files. Excel cells have types, so dates come back as dates.
excel_sample = pd.read_excel("data/sales_sample.xlsx", sheet_name="sales")print(excel_sample.shape)print(excel_sample["order_date"].dtype)(500, 13)datetime64[us]JSON. pd.read_json(path) reads JSON that is already table-shaped: a list of flat records. df.to_json(path, orient="records") writes one: the orient argument chooses the JSON layout, and "records" gives a list with one object per row, the layout that APIs use. lines=True writes or reads JSON Lines instead: one JSON object per line (module 07). Real JSON is often nested. pd.json_normalize(records) flattens nested dicts into columns with dotted names, such as address.city. Example 3 shows both step by step.
Parquet. Parquet is a binary, columnar file format: it stores the file column by column, compressed, together with the dtype of each column. pd.read_parquet reads it back with the exact dtypes. It can also read only some columns, which is fast because each column is stored separately.
parquet_sample = pd.read_parquet( "data/sales_sample.parquet", columns=["order_id", "order_date", "revenue"])print(parquet_sample.dtypes)order_id strorder_date datetime64[us]revenue float64dtype: object| Format | Read / write | Keeps dtypes | Size | Best for |
|---|---|---|---|---|
| CSV | read_csv / to_csv |
no, all text | large | exchange with any tool, small files |
| Excel | read_excel / to_excel |
partly (numbers, dates) | medium | business users, reports |
| JSON | read_json, json_normalize / to_json |
partly | large | APIs, nested records |
| Parquet | read_parquet / to_parquet |
yes, exactly | small | pipelines, big data, caching |
Inspecting a DataFrame
Section titled “Inspecting a DataFrame”Before you analyze a dataset, look at it. Five tools answer the first questions:
| Question | Tool |
|---|---|
| What do the rows look like? | df.head(n), df.tail(n), df.sample(n, random_state=42) |
| How big is it? | df.shape, len(df) |
| Which columns, which dtypes, any gaps, how much memory? | df.info() |
| What are the typical values of each numeric column? | df.describe() |
| How often does each value occur? | df["col"].value_counts() |
print(sales.head(3)) order_id order_date region category quantity revenue0 O000001 2023-01-01 West Home 1 66.491 O000002 2023-01-01 West Clothing 1 14.992 O000003 2023-01-01 South Clothing 1 19.99head(3) shows the first 3 rows. It is the fastest check that the file loaded as you expect.
info() prints a summary of the structure. It prints by itself and returns None, so call it on its own line, not inside print():
sales.info()<class 'pandas.DataFrame'>RangeIndex: 20228 entries, 0 to 20227Data columns (total 6 columns): # Column Non-Null Count Dtype--- ------ -------------- ----- 0 order_id 20228 non-null str 1 order_date 20228 non-null datetime64[us] 2 region 20228 non-null str 3 category 20228 non-null str 4 quantity 20228 non-null int64 5 revenue 20228 non-null float64dtypes: datetime64[us](1), float64(1), int64(1), str(3)memory usage: 1.3 MBRead it from top to bottom: the class, the index (20,228 rows numbered 0 to 20227), one line per column with its count of non-missing values and its dtype, a count of columns per dtype and the memory that the data uses. A non-null count lower than the number of rows means that the column has gaps.
describe() computes summary statistics for each numeric column: the count, mean, standard deviation (std, the typical distance from the mean), minimum, quartiles and maximum. The quartiles are the 25%, 50% and 75% rows: the values below which a quarter, half and three quarters of the rows fall. The 50% row is the median.
print(sales[["quantity", "revenue"]].describe()) quantity revenuecount 20228.000 20228.000mean 1.460 177.799std 1.061 314.840min 1.000 11.99025% 1.000 33.98050% 1.000 79.99075% 2.000 189.990max 25.000 5196.000The mean revenue (177.80) is more than twice the median (79.99). A few expensive lines pull the mean up. A summary that shows this in one line is the reason to call describe() first.
value_counts() builds a frequency table: each distinct value and how often it occurs, the most frequent first. normalize=True gives shares instead of counts:
print(sales["region"].value_counts())print(sales["category"].value_counts(normalize=True).round(3))regionEast 5396South 5144North 4966West 4722Name: count, dtype: int64categoryClothing 0.198Electronics 0.195Sports 0.165Home 0.161Beauty 0.154Books 0.127Name: proportion, dtype: float64Selecting data: [], loc and iloc
Section titled “Selecting data: [], loc and iloc”pandas has three ways to select data. Each answers a different question.
| Syntax | Selects by | Example | Slice end |
|---|---|---|---|
df["col"] |
column name | sales["revenue"] (a Series) |
— |
df[["a", "b"]] |
list of column names | sales[["region", "revenue"]] (a DataFrame) |
— |
df.loc[rows, cols] |
labels | df.loc["H0003":"H0005", "price"] |
included |
df.iloc[rows, cols] |
positions (0, 1, 2…) | df.iloc[0:3, -1] |
excluded |
loc is label-based indexing: you name the rows and columns by their labels. iloc is position-based indexing: you give integer positions, as with a Python list. The difference is clearest with an index that is not 0, 1, 2. Load the houses with house_id as the index:
houses = pd.read_csv("data/houses.csv", index_col="house_id", parse_dates=["sold_date"])print(houses.loc["H0003", "price"])print(houses.loc["H0003":"H0005", ["neighborhood", "sqft", "price"]])223000 neighborhood sqft pricehouse_idH0003 Cedar Park 1260 223000H0004 Downtown 1790 431000H0005 Riverside 3170 626500A loc slice by label includes its end label: "H0003":"H0005" gives 3 rows. Labels have no “next” value, so pandas includes the end so that you can name it.
print(houses.iloc[2:5, [0, 1, -1]])print(houses.iloc[-1]["price"]) neighborhood sqft pricehouse_idH0003 Cedar Park 1260 223000H0004 Downtown 1790 431000H0005 Riverside 3170 626500214500An iloc slice excludes its end, like a list slice: positions 2, 3 and 4. Both selections return the same 3 houses here, because H0003 is at position 2. After a sort or a filter, labels and positions no longer match. Then the choice matters.
Boolean filtering
Section titled “Boolean filtering”To keep the rows that match a condition, build a boolean mask and pass it to [] or loc. A mask is a Series of True/False values, one per row, as in module 23. A comparison on a column builds one:
is_big = sales["revenue"] > 1000print(is_big.head(3))print(is_big.sum(), "lines above 1000 USD")print(sales[is_big].shape)0 False1 False2 FalseName: revenue, dtype: bool969 lines above 1000 USD(969, 6)True counts as 1, so .sum() counts the matching rows. sales[is_big] keeps only the rows where the mask is True.
Combine masks with the element-wise operators & (and), | (or) and ~ (not). Put each comparison in parentheses, because & and | bind more tightly than > and ==:
electronics_big = sales[(sales["category"] == "Electronics") & (sales["quantity"] >= 3)]print(len(electronics_big))not_west = sales[~(sales["region"] == "West")]print(len(not_west), len(sales) - len(not_west))8915506 4722Python’s and, or and not do not work on a Series. They need one True or False for the whole Series, and pandas refuses to guess which one you mean:
print(sales[(sales["quantity"] >= 3) and (sales["revenue"] > 1000)])ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or a.all().Two methods shorten common masks:
col.isin([...])isTruewhere the value is in a list. It replaces a chain of|comparisons.col.between(low, high)isTruewherelow <= value <= high. Both ends are included by default (inclusive="both"). It works for numbers and dates.
north_east = sales["region"].isin(["North", "East"])december_2024 = sales["order_date"].between("2024-12-01", "2024-12-31")print(north_east.sum(), december_2024.sum(), (north_east & december_2024).sum())10362 1667 889pandas converts the text "2024-12-01" to a date for the comparison, because the column is a datetime column.
query(): filters as text
Section titled “query(): filters as text”df.query("expression") filters with a string that reads like a sentence. Inside the string, column names are plain names and and, or and not are allowed. Refer to a Python variable with @:
max_tenure = 6risky = pd.read_csv("data/customers.csv").query( "tenure_months <= @max_tenure and logins_last_30d <= 3")print(risky.shape)(90, 15)query is shorter and easier to read for long conditions. A mask is better when you build the condition step by step in code or reuse it. Column names with spaces need backticks inside a query: `unit price` > 100.
Sorting
Section titled “Sorting”| Method | Sorts by | Example |
|---|---|---|
sort_values(col) |
one column’s values | sales.sort_values("revenue") |
sort_values([a, b], ascending=[True, False]) |
several columns, each with its own direction | region A→Z, then revenue high→low |
sort_index() |
the index labels | restore the original row order |
nlargest(n, col), nsmallest(n, col) |
the top or bottom n rows | sales.nlargest(5, "revenue") |
top = sales.sort_values(["region", "revenue"], ascending=[True, False])print(top[["region", "order_id", "revenue"]].head(4)) region order_id revenue19550 East O014369 4596.008018 East O005945 3897.004224 East O003094 3702.1515818 East O011634 3447.00A multi-key sort sorts by the first key, then breaks ties with the second key. The index labels stay with their rows, so the index is now out of order. sort_index() puts the rows back in index order. ignore_index=True gives the result a fresh 0, 1, 2… index instead.
nlargest is shorter than a full sort followed by head(), and faster on big data, because it does not sort the rest:
print(sales.nlargest(3, "revenue")[["order_id", "category", "quantity", "revenue"]]) order_id category quantity revenue2082 O001531 Electronics 4 5196.09370 O006934 Electronics 4 4596.016116 O011849 Electronics 4 4596.0Missing values go last by default. na_position="first" puts them first. For a stable result when values tie, pass kind="stable": rows with equal keys then keep their original order.
Adding and changing columns
Section titled “Adding and changing columns”A vectorized operation works on a whole column at once, with no Python loop. Column arithmetic is vectorized: sales["revenue"] / sales["quantity"] divides 20,228 pairs of values in one call. Assign the result to a new column name to add a column:
sales["revenue_per_unit"] = sales["revenue"] / sales["quantity"]print(sales[["quantity", "revenue", "revenue_per_unit"]].head(3)) quantity revenue revenue_per_unit0 1 66.49 66.491 1 14.99 14.992 1 19.99 19.99np.where(condition, value_if_true, value_if_false) from NumPy picks one of two values per row. It is the vectorized form of if/else. For three or more branches, np.select(conditions, choices, default=...) takes a list of masks and a list of values, and uses the first mask that is True in each row; exercise M24-X03 uses it.
sales["size"] = np.where(sales["revenue"] >= 500, "large", "small")print(sales["size"].value_counts())sizesmall 18891large 1337Name: count, dtype: int64df.assign(name=values) returns a new DataFrame with the extra columns and leaves the original unchanged. A lambda receives the DataFrame at that point of the chain, so a later column can use an earlier one. This style is called method chaining:
summary = ( sales[["order_id", "quantity", "revenue"]] .assign( revenue_k=lambda d: d["revenue"] / 1000, bulk=lambda d: d["quantity"] >= 10, ) .query("bulk"))print(summary.head(3))print(len(summary), "bulk lines;", "bulk" in sales.columns) order_id quantity revenue revenue_k bulk2942 O002165 12 345.6 0.346 True3589 O002625 18 387.0 0.387 True4544 O003337 14 1253.0 1.253 True29 bulk lines; FalseTo change the values of some rows of a column, use df.loc[mask, column] = value. It selects the rows and the column in one step:
sales["priority"] = "normal"sales.loc[sales["revenue"] >= 2000, "priority"] = "high"print(sales["priority"].value_counts())prioritynormal 20122high 106Name: count, dtype: int64Create the column first with a default value, as here. If loc creates the column, the rows that the mask skips get NaN.
Copy-on-write and chained assignment
Section titled “Copy-on-write and chained assignment”In pandas 3, copy-on-write (CoW) is always on. The rule: every selection or method result behaves as a new, separate object. Changing it never changes the DataFrame it came from. pandas copies the data lazily, only when one of the two objects is modified, so selections stay cheap.
One consequence breaks old code. Chained assignment is an assignment through two selections in a row, such as df["col"][mask] = value. The first selection, df["col"], is a new object. The assignment changes that object, not df. So the line does nothing to df, and pandas warns with a ChainedAssignmentError.
import warnings
demo = pd.DataFrame({"store_id": ["S01", "S12"], "size_sqm": [2850, 1350]})with warnings.catch_warnings(record=True) as caught: # record the warning to print it warnings.simplefilter("always") demo["size_sqm"][demo["store_id"] == "S12"] = 1400 # chained: does nothingprint(caught[0].category.__name__)print(demo["size_sqm"].to_list())demo.loc[demo["store_id"] == "S12", "size_sqm"] = 1400 # one step: worksprint(demo["size_sqm"].to_list())ChainedAssignmentError[2850, 1350][2850, 1400]The warnings.catch_warnings block records the warning so that this page can print its class name. In your own script, the warning appears in the terminal. Do not silence it; rewrite the line with loc.
Drop a second old habit too: the inplace=True argument. pandas 3.1 deprecates it on most methods, including sort_values, sort_index, dropna, drop, rename, set_index, reset_index, drop_duplicates and query. Each of them warns with Pandas4Warning, the deprecation warning for features that pandas 4 removes. A few methods, such as fillna, replace and where, still accept inplace=True without a warning. Under copy-on-write, inplace does not avoid a copy in most cases, and it blocks method chaining.
by_size = demo.copy()with warnings.catch_warnings(record=True) as caught: # record the warning to print it warnings.simplefilter("always") by_size.sort_values("size_sqm", inplace=True) # deprecatedprint(caught[0].category.__name__)print(str(caught[0].message).split(" and ")[0])by_size = demo.sort_values("size_sqm") # the modern form: assign the resultprint(by_size["store_id"].to_list())Pandas4WarningThe inplace keyword in DataFrame.sort_values is deprecated['S12', 'S01']Assign the result instead: df = df.sort_values("revenue"). When you want an independent copy for your own changes, say so with .copy(): subset = df[mask].copy().
Vectorized operations vs apply and map
Section titled “Vectorized operations vs apply and map”df.apply(func, axis=1) calls a Python function once per row. s.map(func) calls it once per value. They are flexible, but each call goes through the Python interpreter. apply(axis=1) also builds a Series object for every row before it calls the function. A vectorized expression runs one compiled loop over the whole column.
| Tool | Runs | Use for |
|---|---|---|
column arithmetic, comparisons, np.where |
compiled loop over columns | almost every calculation |
s.map(dict_or_series) |
fast lookup per value | translating codes with a mapping table |
s.map(func) |
Python call per value | logic with no vectorized form |
df.apply(func, axis=1) |
Python call per row | a last resort; slow on big data |
df.map(func) |
Python call per cell | formatting every cell |
map with a dict is the good use of map. It replaces each value by its entry in the dict, and values with no entry become NaN:
region_manager = {"North": "Kim", "South": "Diaz", "East": "Osei", "West": "Novak"}print(sales["region"].map(region_manager).head(3).to_list())['Novak', 'Novak', 'Diaz']Example 7 times apply against the vectorized formula on all 20,228 lines.
Converting dtypes
Section titled “Converting dtypes”Three tools change the dtype of a column:
| Tool | Use when | Failure |
|---|---|---|
s.astype(dtype) |
every value converts cleanly: "int32", "float64", "category", "str" |
raises an error on the first bad value |
pd.to_numeric(s, errors="coerce") |
text that should be numbers but has bad entries | bad values become NaN |
pd.to_datetime(s, format=...) |
text dates | errors="coerce" turns bad values into NaT |
To coerce a value means to force it into the target type and accept NaN for values that cannot convert. Coercion hides failures as NaN. Count the gaps before and after, so that you see every value that failed:
raw_prices = pd.Series(["79.99", "249.00", "n/a", "1299.00"])as_numbers = pd.to_numeric(raw_prices, errors="coerce")print(as_numbers.to_list())print(as_numbers.isna().sum(), "value could not convert")[79.99, 249.0, nan, 1299.0]1 value could not convertastype is strict. It stops at the first value it cannot convert:
print(raw_prices.astype("float64"))ValueError: could not convert string to float: 'n/a'Categoricals
Section titled “Categoricals”A categorical column stores each distinct value once, in a list called the categories, and stores every row as a small integer code that points into that list. A column such as plan has 5,000 rows but only 3 distinct values. Storing 3 strings and 5,000 small integers takes far less memory than 5,000 strings.
flowchart LR
R["rows: premium, standard, premium, basic"] --> K["codes: 1, 2, 1, 0<br/>int8"]
K --> C["categories, sorted A to Z:<br/>0 basic, 1 premium, 2 standard"]
An ordered categorical also knows the order of its categories. Then <, >=, min, max and sorting follow that order instead of the alphabet. Create one with pd.CategoricalDtype(categories, ordered=True). Example 8 measures the memory and uses the order.
Use category for text columns with few distinct values, many repeats and a fixed set of allowed values: regions, plans, contract types, status codes. Do not use it for ids or free text, where almost every value is distinct.
Worked examples
Section titled “Worked examples”Example 1 — Load and profile the sales file
Section titled “Example 1 — Load and profile the sales file”Goal: A new analyst gets data/sales.csv (20,228 order lines). Load it with the right dtypes and answer the first questions: how big is it, are there gaps, what are typical values and which regions and channels dominate?
Step 1 — Load with the right options
Section titled “Step 1 — Load with the right options”sales = pd.read_csv( "data/sales.csv", parse_dates=["order_date"], dtype={"region": "category", "channel": "category", "category": "category"},)print(sales.shape)print(sales.dtypes[["order_date", "region", "channel", "category", "revenue"]])(20228, 13)order_date datetime64[us]region categorychannel categorycategory categoryrevenue float64dtype: objectparse_dates makes order_date a datetime column. The dtype dict loads three text columns as categoricals at read time. They have a low cardinality: the number of distinct values in a column. region has 4. .dtypes is itself a Series, so a list of labels selects some of its entries.
Step 2 — Check the structure with info()
Section titled “Step 2 — Check the structure with info()”sales.info()<class 'pandas.DataFrame'>RangeIndex: 20228 entries, 0 to 20227Data columns (total 13 columns): # Column Non-Null Count Dtype--- ------ -------------- ----- 0 order_id 20228 non-null str 1 order_date 20228 non-null datetime64[us] 2 customer_id 20228 non-null str 3 store_id 20228 non-null str 4 region 20228 non-null category 5 channel 20228 non-null category 6 product_id 20228 non-null str 7 product 20228 non-null str 8 category 20228 non-null category 9 unit_price 20228 non-null float64 10 quantity 20228 non-null int64 11 discount 20228 non-null float64 12 revenue 20228 non-null float64dtypes: category(3), datetime64[us](1), float64(3), int64(1), str(5)memory usage: 2.4 MBEvery column has 20,228 non-null values, so the file has no gaps. The three categoricals already shrink the memory: a load with the default options reports 3.3 MB.
Step 3 — Summarize the numeric columns
Section titled “Step 3 — Summarize the numeric columns”print(sales[["unit_price", "quantity", "discount", "revenue"]].describe()) unit_price quantity discount revenuecount 20228.000 20228.000 20228.000 20228.000mean 146.333 1.460 0.033 177.799std 253.811 1.061 0.058 314.840min 14.990 1.000 0.000 11.99025% 24.990 1.000 0.000 33.98050% 69.990 1.000 0.000 79.99075% 129.990 2.000 0.050 189.990max 1299.000 25.000 0.200 5196.000At least 75% of lines have quantity 1 or 2, but the maximum is 25: a few bulk orders exist. Discounts range from 0 to 0.2. The maximum line revenue is 5,196 USD.
Step 4 — Count the categories
Section titled “Step 4 — Count the categories”print(sales["channel"].value_counts(normalize=True).round(3))print(sales["order_date"].min(), "to", sales["order_date"].max())print(sales["order_id"].nunique(), "orders in", len(sales), "lines")channelstore 0.58online 0.42Name: proportion, dtype: float642023-01-01 00:00:00 to 2024-12-31 00:00:0014877 orders in 20228 lines42% of lines are online. The data covers two full years. nunique() counts distinct values: 14,877 orders have 20,228 lines, so order_id is not unique per row. That fact matters later, when you count orders instead of lines.
Common mistakes:
- Writing
print(sales.info()). It prints the summary and thenNone. Callsales.info()alone. - Skipping
parse_dates.sales["order_date"].min()then compares text, which works for ISO dates by luck but fails for07/01/2023, and date arithmetic raises aTypeError. - Judging a dataset by
head()alone. The first rows are all from 2023-01-01;describe()andvalue_counts()show the whole file.
Example 2 — Move a sales sample between Excel, Parquet and CSV
Section titled “Example 2 — Move a sales sample between Excel, Parquet and CSV”Goal: Finance sends data/sales_sample.xlsx. The data team keeps the same 500 lines as data/sales_sample.parquet. Check that both hold the same data, then write a cleaned copy in three formats to output/ and compare what each format keeps.
Step 1 — Read the Excel workbook
Section titled “Step 1 — Read the Excel workbook”with pd.ExcelFile("data/sales_sample.xlsx") as workbook: print(workbook.sheet_names) from_excel = pd.read_excel(workbook, sheet_name="sales")print(from_excel.shape)print(from_excel[["order_id", "order_date", "product", "revenue"]].head(3))['sales'](500, 13) order_id order_date product revenue0 O000001 2023-01-01 Cotton Bed Sheet Set 66.491 O000002 2023-01-01 Running Socks 3-Pack 14.992 O000003 2023-01-01 Organic Cotton T-Shirt 19.99pd.ExcelFile opens the workbook once and lists its sheets. read_excel then reads the sheet named sales. The with block closes the file at the end, as in module 07. The Excel date cells arrive as datetime64 values.
Step 2 — Compare with the Parquet copy
Section titled “Step 2 — Compare with the Parquet copy”from_parquet = pd.read_parquet("data/sales_sample.parquet")print(from_parquet.dtypes["order_date"])print(from_excel.equals(from_parquet))datetime64[us]Truedf.equals(other) is True only when both frames have the same shape, the same values (with NaN equal to NaN) and the same dtypes. The two files hold identical data.
Step 3 — Write the sample in three formats
Section titled “Step 3 — Write the sample in three formats”sample = from_parquet.astype({"region": "category", "category": "category"})sample.to_csv("output/sample.csv", index=False)sample.to_excel("output/sample.xlsx", sheet_name="sales", index=False)sample.to_parquet("output/sample.parquet", index=False)for name in ["sample.csv", "sample.xlsx", "sample.parquet"]: size_kb = Path("output", name).stat().st_size / 1024 print(f"{name:<15} {size_kb:5.1f} KB")sample.csv 45.9 KBsample.xlsx 35.6 KBsample.parquet 16.2 KBastype with a dict converts several columns at once. All three files hold the same 500 rows. The sizes differ because each format stores the data differently.
Step 4 — Read each file back and compare dtypes
Section titled “Step 4 — Read each file back and compare dtypes”round_trip = pd.DataFrame( { "csv": pd.read_csv("output/sample.csv").dtypes, "excel": pd.read_excel("output/sample.xlsx").dtypes, "parquet": pd.read_parquet("output/sample.parquet").dtypes, })print(round_trip.loc[["order_date", "region", "quantity"]])print(pd.read_parquet("output/sample.parquet").equals(sample)) csv excel parquetorder_date str datetime64[us] datetime64[us]region str str categoryquantity int64 int64 int64TrueA DataFrame built from a dict of Series aligns the Series by their index, here the column names. CSV loses both the dates and the categories. Excel keeps dates but not categories. Parquet returns the exact frame.
Common mistakes:
- Forgetting
index=False. The file gets an extra column; reading it back showsUnnamed: 0. - Writing outputs into
data/. Keep raw inputs untouched and write results tooutput/. - Expecting
read_excelto read every sheet. It reads the first sheet unless you passsheet_name.sheet_name=Nonereturns a dict of all sheets.
Example 3 — Flatten nested customer JSON
Section titled “Example 3 — Flatten nested customer JSON”Goal: The CRM exports data/customers.json: 20 customers, each with a nested address and a list of orders. Build two flat tables, one row per customer and one row per order, and save them for analysis.
Step 1 — Load the JSON and look at one record
Section titled “Step 1 — Load the JSON and look at one record”import json
with open("data/customers.json", encoding="utf-8") as f: export = json.load(f)print(list(export))first = export["customers"][0]print(list(first))print(first["address"])naive = pd.read_json("data/customers.json")print(naive.shape, naive.columns.to_list())['exported_at', 'count', 'customers']['customer_id', 'name', 'email', 'signup_date', 'plan', 'address', 'tags', 'orders', 'phone']{'street': '546 Park Blvd', 'city': 'Chicago', 'region': 'North', 'postal_code': '81790'}(20, 3) ['exported_at', 'count', 'customers']The records sit under the key customers, next to export metadata. Each record has a nested address dict and an orders list. pd.read_json on this file gives a 20 × 3 frame: exported_at and count repeated on every row, and a customers column whose cells are whole dicts. That is not useful for analysis.
Step 2 — Flatten one row per customer
Section titled “Step 2 — Flatten one row per customer”customers_flat = pd.json_normalize(export["customers"])print(customers_flat.shape)print(customers_flat.columns[:8].to_list())print(customers_flat.columns[8:].to_list())(20, 12)['customer_id', 'name', 'email', 'signup_date', 'plan', 'tags', 'orders', 'phone']['address.street', 'address.city', 'address.region', 'address.postal_code']json_normalize turned each key of the nested address dict into its own column with a dotted name. The lists tags and orders stay as single object cells, because a list does not fit in one flat row.
Step 3 — Flatten one row per order
Section titled “Step 3 — Flatten one row per order”orders = pd.json_normalize( export["customers"], record_path="orders", meta=["customer_id", "plan"])print(orders.shape)print(orders.head(3))(48, 6) order_id date items amount customer_id plan0 O000614 2023-02-18 1 32.00 C00001 premium1 O004814 2023-10-20 2 31.98 C00001 premium2 O004967 2023-10-30 2 107.98 C00001 premiumrecord_path="orders" makes one row per item of each customer’s orders list. meta copies fields of the parent record onto each order row, so every order knows its customer. Customers with an empty orders list produce no rows: 48 orders in total.
Step 4 — Clean the column names and save
Section titled “Step 4 — Clean the column names and save”customers_table = ( customers_flat.drop(columns=["tags", "orders"]) .rename(columns=lambda name: name.replace("address.", "")))print(customers_table[["customer_id", "city", "region", "postal_code"]].head(3))print(customers_table["phone"].isna().sum(), "customers without a phone")customers_table.to_csv("output/customers_flat.csv", index=False)orders.to_parquet("output/customer_orders.parquet", index=False) customer_id city region postal_code0 C00001 Chicago North 817901 C00002 Denver West 622602 C00003 San Francisco West 4591514 customers without a phonedrop(columns=...) removes the list columns. rename(columns=func) calls the function on every column name. Missing keys became NaN: the phone key is absent or null for most customers, and json_normalize fills both cases with NaN.
Step 5 — Round-trip the orders through JSON
Section titled “Step 5 — Round-trip the orders through JSON”orders.to_json("output/orders.json", orient="records", indent=2)with open("output/orders.json", encoding="utf-8") as f: print("\n".join(f.read().splitlines()[:9])) # the first recordback = pd.read_json("output/orders.json")print(back.dtypes)[ { "order_id":"O000614", "date":"2023-02-18", "items":1, "amount":32.0, "customer_id":"C00001", "plan":"premium" },order_id strdate datetime64[us]items int64amount float64customer_id strplan strdtype: objectorient="records" writes a list with one JSON object per row, and indent=2 makes the file readable. read_json turns the list back into a frame. JSON has no date type, so the file stores date as text. read_json still returns a datetime column, because it guesses dates from column names: a column named date, modified or datetime, or one whose name ends in _at or _time or starts with timestamp, is parsed as a date.
Step 6 — Write JSON Lines and parse the dates yourself
Section titled “Step 6 — Write JSON Lines and parse the dates yourself”renamed = orders.rename(columns={"date": "order_date"})renamed.to_json("output/orders.jsonl", orient="records", lines=True)lines_back = pd.read_json("output/orders.jsonl", lines=True)print(len(lines_back), lines_back["order_date"].dtype)lines_back["order_date"] = pd.to_datetime(lines_back["order_date"], format="%Y-%m-%d")print(lines_back["order_date"].dtype)48 strdatetime64[us]lines=True writes one object per line, the JSON Lines format of module 07; log files and data pipelines use it, because a reader can process the file line by line. The name order_date matches none of the name rules, so it comes back as str. Do not rely on the guess: parse date columns explicitly with pd.to_datetime. If a frame has a datetime column, pass date_format="iso" to to_json; pandas 3.1 warns with Pandas4Warning without it, because its default date format will change.
Common mistakes:
- Passing the whole
exportdict tojson_normalize. You get one row with the metadata. Pass the list of records:export["customers"]. - Forgetting
meta. The order rows then have nocustomer_id, and you cannot link them back to a customer. - Reading
0orders as missing data. Three customers have an empty list; they are real customers with no orders.
Example 4 — Find the top orders of the holiday season
Section titled “Example 4 — Find the top orders of the holiday season”Goal: The marketing team asks for the biggest online Electronics lines between Black Friday (2024-11-29) and the end of 2024, and for the share of those lines in the North and East regions.
Step 1 — Build one mask per rule
Section titled “Step 1 — Build one mask per rule”in_season = sales["order_date"].between("2024-11-29", "2024-12-31")online = sales["channel"] == "online"electronics = sales["category"] == "Electronics"print(in_season.sum(), online.sum(), electronics.sum())1958 8495 3942Each mask has one True or False per line. Naming the masks makes the rule readable and lets you check each part on its own.
Step 2 — Combine the masks and select columns
Section titled “Step 2 — Combine the masks and select columns”cols = ["order_date", "order_id", "region", "product", "quantity", "revenue"]season = sales.loc[in_season & online & electronics, cols]print(season.shape)print(season["revenue"].sum().round(2))(260, 6)100275.45loc takes the mask for the rows and the list for the columns in one call. The result is a new, smaller DataFrame.
Step 3 — Sort by two keys and take the top lines
Section titled “Step 3 — Sort by two keys and take the top lines”ranked = season.sort_values(["revenue", "order_date"], ascending=[False, True])print(ranked.head(5)) order_date order_id region product quantity revenue19815 2024-12-22 O014571 East 55-inch 4K Smart TV 3 3117.618441 2024-11-29 O013552 East 55-inch 4K Smart TV 2 2468.120007 2024-12-27 O014718 South 14-inch Ultrabook Laptop 2 2298.018430 2024-11-29 O013545 North 55-inch 4K Smart TV 2 2078.420160 2024-12-30 O014828 North 14-inch Ultrabook Laptop 2 2068.2The first key orders by revenue, highest first. When two lines have the same revenue, the second key puts the earlier date first. The index still shows each line’s position in the full file.
Step 4 — Measure the regional share with isin
Section titled “Step 4 — Measure the regional share with isin”north_east = season["region"].isin(["North", "East"])print(f"North + East: {north_east.mean():.1%} of lines")print(season.nlargest(3, "quantity")[["order_id", "product", "quantity"]])North + East: 58.8% of lines order_id product quantity18277 O013431 Wireless Earbuds 419588 O014397 Wireless Earbuds 420116 O014799 Wireless Earbuds 4The mean of a boolean mask is the share of True values. nlargest gives the three lines with the most units without a full sort; ties keep their file order.
Common mistakes:
- Leaving out the parentheses:
sales["channel"] == "online" & electronicsevaluates"online" & electronicsfirst and raises aTypeError. - Using
andbetween masks. It raisesValueError: The truth value of a Series is ambiguous. - Forgetting that
betweenincludes both ends. That is right here: Black Friday and 31 December both count.
Example 5 — Add price features to the house data
Section titled “Example 5 — Add price features to the house data”Goal: A real-estate analyst prepares data/houses.csv for a price model. Add the price per square foot, the age of each house at sale, a size class and a flag for top schools, without changing any original column.
Step 1 — Compute two features with vectorized arithmetic
Section titled “Step 1 — Compute two features with vectorized arithmetic”houses = pd.read_csv("data/houses.csv", parse_dates=["sold_date"])houses["price_per_sqft"] = houses["price"] / houses["sqft"]houses["age_at_sale"] = houses["sold_date"].dt.year - houses["year_built"]print(houses[["house_id", "sqft", "price", "price_per_sqft", "age_at_sale"]].head(3)) house_id sqft price price_per_sqft age_at_sale0 H0001 2420 1097500 453.512 61 H0002 1610 486500 302.174 42 H0003 1260 223000 176.984 30Each line computes 3,000 values at once. .dt.year takes the year of each date; module 25 covers the .dt accessor in full.
Step 2 — Classify with np.where
Section titled “Step 2 — Classify with np.where”houses["size_class"] = np.where(houses["sqft"] >= 2500, "large", "standard")print(houses["size_class"].value_counts())size_classstandard 2512large 488Name: count, dtype: int64np.where checks the condition for each row and picks "large" or "standard". pandas stores the result as a str column.
Step 3 — Flag top schools with loc
Section titled “Step 3 — Flag top schools with loc”houses["top_school"] = Falsehouses.loc[houses["school_rating"] >= 8, "top_school"] = Trueprint(houses["top_school"].value_counts())print(houses["school_rating"].isna().sum(), "houses have no rating")top_schoolFalse 2088True 912Name: count, dtype: int6490 houses have no ratingNaN >= 8 is False, so the 90 houses without a rating keep the default False. Decide whether that is what you want: here it means “not known to be a top school”.
Step 4 — Build a feature table with assign and query
Section titled “Step 4 — Build a feature table with assign and query”features = ( houses.assign( log_price=lambda d: np.log(d["price"]), rooms=lambda d: d["bedrooms"] + d["bathrooms"], ) .query("size_class == 'large' and top_school") .loc[:, ["house_id", "neighborhood", "rooms", "price_per_sqft", "log_price"]])print(features.shape)print(features.head(3))(251, 5) house_id neighborhood rooms price_per_sqft log_price19 H0020 Lakeview 9.5 407.460 14.06522 H0023 Oak Hill 12.5 444.552 14.74433 H0034 Oak Hill 7.5 350.352 13.810assign adds two columns, query keeps large houses with a top school and .loc[:, cols] selects the columns. : means “all rows”. np.log works on a whole Series, like every NumPy function that works element by element. houses itself keeps its 18 columns: the 14 original ones and the 4 added in steps 1 to 3.
Common mistakes:
- Writing
houses["top_school"][mask] = True. That is chained assignment: under copy-on-write it changes nothing. - Creating the flag with
localone. The rows outside the mask becomeNaN, and the column gets theobjectdtype. - Dividing by a column that contains 0. pandas gives
infinstead of an error; check(houses["sqft"] == 0).sum()first.
Example 6 — Repair the column types of a raw export
Section titled “Example 6 — Repair the column types of a raw export”Goal: data/sales_raw.csv comes from an old point-of-sale system. Prices are text such as $1,299.00, missing values are written as - and dates use three formats. Give unit_price, discount and order_date usable dtypes and count what could not convert.
Step 1 — Load and look at the dtypes
Section titled “Step 1 — Load and look at the dtypes”raw = pd.read_csv("data/sales_raw.csv", na_values=["-"])print(raw[["order_date", "unit_price", "discount", "quantity"]].dtypes)print(raw[["order_date", "unit_price", "discount"]].iloc[6:10])order_date strunit_price strdiscount float64quantity int64dtype: object order_date unit_price discount6 2023-01-07 $14.99 0.007 07/01/2023 $19.99 0.008 January 7, 2023 $129.95 0.009 10/01/2023 $69.99 0.05read_csv already treats empty cells and N/A as missing. na_values=["-"] adds the dash, so discount loads as float64. unit_price is still str because of the dollar signs. Rows 7 and 8 show the two other date formats.
Step 2 — Convert the prices with to_numeric
Section titled “Step 2 — Convert the prices with to_numeric”missing_before = raw["unit_price"].isna().sum()price_text = raw["unit_price"].str.replace("$", "").str.replace(",", "")raw["unit_price"] = pd.to_numeric(price_text, errors="coerce")print(raw["unit_price"].dtype, missing_before, raw["unit_price"].isna().sum())print(raw["unit_price"].max())float64 10 101299.0.str.replace removes the $ and the thousands separator from each text value; module 25 covers the .str accessor. to_numeric converts the rest. The count before the conversion and the count after it are both 10. So the 10 NaN values are the genuinely missing prices, and no value failed to convert.
Step 3 — Parse each date format explicitly
Section titled “Step 3 — Parse each date format explicitly”text_dates = raw["order_date"]iso = pd.to_datetime(text_dates, format="%Y-%m-%d", errors="coerce")day_first = pd.to_datetime(text_dates, format="%d/%m/%Y", errors="coerce")spelled = pd.to_datetime(text_dates, format="%B %d, %Y", errors="coerce")print(iso.notna().sum(), day_first.notna().sum(), spelled.notna().sum())raw["order_date"] = iso.fillna(day_first).fillna(spelled)print(raw["order_date"].dtype, raw["order_date"].isna().sum())print(raw["order_date"].iloc[6:10].dt.strftime("%Y-%m-%d").to_list())723 276 201datetime64[us] 0['2023-01-07', '2023-01-07', '2023-01-07', '2023-01-10']Each call parses one known format and coerces the other values to NaT. %d/%m/%Y reads 07/01/2023 as 7 January, as the source system meant. fillna(other) fills each gap with the value at the same label in other, so the three partial results combine into one column with no NaT left. dt.strftime formats each date as text for a compact print.
Step 4 — Check the shortcut against the explicit parse
Section titled “Step 4 — Check the shortcut against the explicit parse”guessed = pd.to_datetime(text_dates, format="mixed", dayfirst=True)wrong = guessed != raw["order_date"]print(wrong.sum(), "dates differ")print(text_dates[wrong].iloc[0], "->", guessed[wrong].iloc[0].date())269 dates differ2023-01-04 -> 2023-04-01format="mixed" guesses the format of each value on its own, and dayfirst=True applies to every value. So pandas reads the ISO date 2023-01-04 as year, day, month: 1 April. The shortcut parses every row without an error and is still wrong on hundreds of rows. When you know the formats, name them.
Step 5 — Downcast the quantity and verify
Section titled “Step 5 — Downcast the quantity and verify”raw["quantity"] = raw["quantity"].astype("int32")print(raw[["order_date", "unit_price", "quantity", "discount"]].dtypes)check = raw["unit_price"] * raw["quantity"] * (1 - raw["discount"])print((check - raw["revenue"]).abs().le(0.01).mean().round(3))order_date datetime64[us]unit_price float64quantity int32discount float64dtype: object0.963To downcast is to convert a column to a smaller dtype that still holds its values. int32 uses half the memory of int64 and holds values up to about 2.1 billion. The final check recomputes revenue from the repaired columns. 96.3% of lines agree to the cent. The rest have a missing price or discount (NaN makes the comparison False), or one of the 10 negative or absurd quantities that module 26 cleans.
Common mistakes:
- Calling
astype("float64")on the price text. It raisesValueError: could not convert string to float: '$249.00'. - Using
errors="coerce"without counting theNaNvalues. Coercion turns every bad value into a gap silently. - Parsing day-first dates as month-first.
07/01/2023becomes 1 July, and nothing warns you. Name the format:format="%d/%m/%Y". - Trusting
format="mixed", dayfirst=Trueon a column that also has ISO dates. It turns2023-01-04into 1 April.
Example 7 — Replace a slow apply with a vectorized formula
Section titled “Example 7 — Replace a slow apply with a vectorized formula”Goal: A colleague’s script recomputes the revenue of every line with apply. It takes too long on the full history. Show that the vectorized formula gives the same result and measure how much faster it is.
Step 1 — Time the apply version
Section titled “Step 1 — Time the apply version”import time
def line_revenue(row: pd.Series) -> float: return round(row["unit_price"] * row["quantity"] * (1 - row["discount"]), 2)
start = time.perf_counter()slow = sales.apply(line_revenue, axis=1)apply_seconds = time.perf_counter() - startprint(len(slow), slow.head(3).to_list())20228 [66.49, 14.99, 19.99]axis=1 passes one row at a time to the function, as a Series. pandas builds 20,228 row objects and makes 20,228 Python calls. time.perf_counter() measures the elapsed time, as in module 15.
Step 2 — Time the vectorized version
Section titled “Step 2 — Time the vectorized version”start = time.perf_counter()fast = (sales["unit_price"] * sales["quantity"] * (1 - sales["discount"])).round(2)vector_seconds = time.perf_counter() - startprint(fast.head(3).to_list())print("more than 20x faster:", apply_seconds > 20 * vector_seconds)[66.49, 14.99, 19.99]more than 20x faster: TrueThe formula is the same, written on columns. Each operator runs one compiled loop over 20,228 values. The speedup is often 100 times or more; the factor depends on the machine and varies from run to run, so the page prints a comparison.
Step 3 — Check that both give the same numbers
Section titled “Step 3 — Check that both give the same numbers”print("largest apply difference:", (slow - sales["revenue"]).abs().max().round(2))print("vectorized matches exactly:", (fast == sales["revenue"]).all())print((slow != fast).sum(), "lines differ by one cent")largest apply difference: 0.01vectorized matches exactly: True179 lines differ by one centBoth results agree with the file to within one cent. They differ on 179 lines because Python’s round() and NumPy’s rounding (used by Series.round) can round a float near a half cent differently. The data dictionary says that revenue is rounded to cents with np.round, so the vectorized version matches it exactly.
Step 4 — Use map for a lookup, not for arithmetic
Section titled “Step 4 — Use map for a lookup, not for arithmetic”products = pd.read_csv("data/products.csv", index_col="product_id")unit_cost = sales["product_id"].map(products["unit_cost"])gross_profit = sales["revenue"] - unit_cost * sales["quantity"]print(f"gross profit {gross_profit.sum():,.2f} USD")print(f"margin {gross_profit.sum() / sales['revenue'].sum():.1%}")gross profit 1,760,135.83 USDmargin 48.9%map with a Series looks each product_id up in the index of products["unit_cost"]. This is a vectorized lookup, so it is fast. The result then joins ordinary column arithmetic. Module 25 shows the same lookup as a merge.
Common mistakes:
- Reaching for
applyfirst. Ask “can I write this with column operators,np.whereor a NumPy function?” The answer is almost always yes. - Timing a single run of a very fast operation and trusting the exact number. Compare, or repeat with
timeit. - Using
applyfor a dict lookup.s.map(mapping)does it without a Python call per row.
Example 8 — Shrink and order customer plans with categoricals
Section titled “Example 8 — Shrink and order customer plans with categoricals”Goal: data/customers.csv has four text columns with few distinct values. Measure how much memory categoricals save, then make plan an ordered categorical so that “standard or better” is a simple comparison.
Step 1 — Measure the text columns
Section titled “Step 1 — Measure the text columns”customers = pd.read_csv("data/customers.csv")text_cols = ["region", "plan", "contract", "payment_method"]print(customers[text_cols].nunique().to_dict())before = customers[text_cols].memory_usage(deep=True, index=False)print(before.sum(), "bytes as str"){'region': 4, 'plan': 3, 'contract': 3, 'payment_method': 4}333016 bytes as strmemory_usage(deep=True) counts the bytes of each column, including the text itself. index=False leaves out the index. The four columns have 3 or 4 distinct values each, across 5,000 rows.
Step 2 — Convert to category and measure again
Section titled “Step 2 — Convert to category and measure again”as_category = customers[text_cols].astype("category")after = as_category.memory_usage(deep=True, index=False)print(after.sum(), "bytes as category")print(f"{before.sum() / after.sum():.0f}x smaller")print(as_category["plan"].cat.categories.to_list())20230 bytes as category16x smaller['basic', 'premium', 'standard']Each row now stores a 1-byte code instead of a string. The .cat accessor gives the categorical parts: .cat.categories lists the distinct values, sorted alphabetically by default. The saving grows with the number of rows.
Step 3 — Define the plan order
Section titled “Step 3 — Define the plan order”plan_order = pd.CategoricalDtype(["basic", "standard", "premium"], ordered=True)customers["plan"] = customers["plan"].astype(plan_order)print(customers["plan"].head(3))print(customers["plan"].cat.codes.head(3).to_list())0 premium1 standard2 premiumName: plan, dtype: categoryCategories (3, str): ['basic' < 'standard' < 'premium'][2, 1, 2]The dtype line shows the order with < signs. The codes follow the order you gave: basic is 0 and premium is 2. An alphabetical order would put premium before standard, which makes no business sense.
Step 4 — Compare and sort by the order
Section titled “Step 4 — Compare and sort by the order”upgraded = customers["plan"] >= "standard"print(upgraded.sum(), "customers on standard or premium")by_plan = customers.sort_values("plan", ascending=False, kind="stable")print(by_plan[["customer_id", "plan", "monthly_charges"]].head(3))print(customers["plan"].value_counts(sort=False))2972 customers on standard or premium customer_id plan monthly_charges0 C00001 premium 84.692 C00003 premium 108.023 C00004 premium 85.25planbasic 2028standard 1982premium 990Name: count, dtype: int64>= compares the position in the category order, not the text. The sort puts premium first. value_counts(sort=False) lists the counts in category order instead of by size, which reads well in a report.
Common mistakes:
- Comparing an unordered categorical with
>=. pandas raises aTypeError; defineordered=True. - Assigning a value that is not a category, such as
"enterprise". pandas raises aTypeError; add the category first with.cat.add_categories. - Converting an id column such as
customer_idtocategory. Every value is distinct, so the categories cost more memory than they save.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
df[(a > 1) and (b < 2)] |
ValueError: The truth value of a Series is ambiguous |
Use &, |, ~ with parentheses around each comparison |
df[df.a > 1 & df.b < 2] |
ValueError, TypeError or a wrong result |
Parentheses: (df.a > 1) & (df.b < 2) |
df["col"][mask] = value |
ChainedAssignmentError warning; df unchanged |
df.loc[mask, "col"] = value |
print(df.info()) |
An extra None after the summary |
Call df.info() alone |
to_csv("x.csv") without index=False |
Unnamed: 0 column when read back |
to_csv("x.csv", index=False) |
| Dates left as text | TypeError in date arithmetic; wrong min/max for non-ISO dates |
parse_dates=[...] or pd.to_datetime |
astype(float) on dirty text |
ValueError: could not convert string to float |
pd.to_numeric(s, errors="coerce") and count the NaN |
loc slice expected to exclude its end |
One row too many | loc includes the end label; iloc excludes the end position |
iloc after a sort or filter, expecting labels |
Wrong rows | Use loc with labels, or reset_index(drop=True) first |
| Integer column with a blank cell | dtype float64 instead of int64 |
Expected; use "Int64" if you need whole numbers with gaps |
inplace=True on sort_values, dropna, drop, rename… |
Pandas4Warning: The inplace keyword … is deprecated |
Assign the result: df = df.dropna() |
apply(axis=1) for arithmetic |
Slow on large frames | Column arithmetic, np.where, map with a dict |
>= on an unordered categorical |
TypeError |
pd.CategoricalDtype([...], ordered=True) |
| Arithmetic between Series with different labels | Unexpected NaN values |
Check the indexes; align them first, or use .to_numpy() on purpose |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: an admin dashboard loads a database export with
read_csv, filters it with masks and sendsdf.to_json(orient="records")to the browser. - Automation: a nightly script merges Excel files from several teams with
read_excel, fixes types withto_numericand writes one Parquet file for the data warehouse. - Finance and operations: analysts replace spreadsheet formulas with
np.whereand vectorized columns, so a 50,000-row report recalculates in milliseconds and the logic lives in version control. - Tooling: test suites compare expected and actual tables with
df.equalsorpd.testing.assert_frame_equal, and log processors turn JSON log lines into DataFrames withjson_normalize.
Summary
Section titled “Summary”- A Series is one labeled column; a DataFrame is a table of Series that share an index.
.index,.columns,.dtypes,.shapeand.to_numpy()describe them. - In pandas 3, text has the
strdtype and copy-on-write is always on. read_csvoptions fix types at load time:parse_dates,dtype,usecols,na_values. Parquet keeps dtypes exactly; CSV keeps only text. Write outputs tooutput/withindex=False.- Inspect first:
head,info,describe,shape,value_counts. locselects by labels and includes the slice end;ilocselects by positions and excludes it.queryfilters with a readable string.- Combine masks with
&,|,~and parentheses.isinandbetweenshorten common conditions. - Sort with
sort_values(multi-key, per-key direction),sort_indexandnlargest. - Add columns with vectorized arithmetic,
np.whereandassign. Change some rows withdf.loc[mask, col] = value, never with chained assignment. - Vectorized code is often 100 times faster than
apply, or more; the factor depends on the machine. Usemapwith a dict or Series for lookups. - Convert with
astype(strict),pd.to_numeric(errors="coerce")andpd.to_datetime, and count the new gaps. Categoricals save memory, and ordered categoricals compare and sort in business order.
Self-check questions
Section titled “Self-check questions”Q1. What is the difference between a Series and a DataFrame?
Answer
A Series is one column of values of one dtype, with an index of labels. A DataFrame is a table of several columns. Each column is a Series, and all columns share one index. df["col"] returns a Series; df[["col"]] returns a one-column DataFrame.
Q2. pd.read_csv("data/sales.csv") gives order_date the dtype str. Name two ways to get a datetime column.
Answer
Pass parse_dates=["order_date"] to read_csv, or convert after loading with sales["order_date"] = pd.to_datetime(sales["order_date"]). Both give datetime64[us].
Q3. houses has house_id as its index. How many rows does houses.loc["H0010":"H0012"] return, and how many does houses.iloc[10:12] return?
Answer
3 and 2. A loc slice includes its end label (H0010, H0011, H0012). An iloc slice excludes its end position (positions 10 and 11).
Q4. Why does sales[sales["quantity"] > 2 and sales["discount"] > 0] fail? Write the correct filter.
Answer
and needs one truth value for each side, but each side is a Series of many values, so pandas raises ValueError: The truth value of a Series is ambiguous. Write sales[(sales["quantity"] > 2) & (sales["discount"] > 0)], with parentheses around each comparison.
Q5. What does this line do in pandas 3, and how do you fix it? sales["discount"][sales["region"] == "West"] = 0
Answer
Nothing to sales. It is chained assignment: sales["discount"] is a separate object under copy-on-write, so the assignment changes only that object, and pandas warns with ChainedAssignmentError. Fix: sales.loc[sales["region"] == "West", "discount"] = 0.
Q6. You need the 10 houses with the highest price. Give two ways and say which is faster on large data.
Answer
houses.sort_values("price", ascending=False).head(10) and houses.nlargest(10, "price"). nlargest is faster, because it finds the top 10 without sorting all rows.
Q7. A column of prices loads as str because three cells contain "n/a". Why is pd.to_numeric(s, errors="coerce") better than s.astype(float) here, and what must you check afterwards?
Answer
astype(float) raises a ValueError at the first "n/a". to_numeric(errors="coerce") converts every valid value and turns the bad ones into NaN. Afterwards, count the NaN values (.isna().sum()) and compare with the gaps you expected, so that no real data was lost silently.
Q8. Why is df["a"] * df["b"] much faster than df.apply(lambda r: r["a"] * r["b"], axis=1)?
Answer
The vectorized product runs one compiled loop over the two columns. apply with axis=1 builds a Series for every row and calls the Python function once per row, so the interpreter does the work row by row. On 20,000 rows, vectorized code is often 100 times faster or more; the factor depends on the machine.
Q9. When does converting a column to category save memory, and when does it waste memory?
Answer
It saves memory when the column has few distinct values that repeat many times, such as plan (3 values in 5,000 rows): each row stores a 1-byte code. It wastes memory on columns where almost every value is distinct, such as customer_id, because the categories then store every value plus the codes.
Q10. What is the difference between an unordered and an ordered categorical?
Answer
Both store codes and categories. An ordered categorical also defines an order, for example basic < standard < premium. Then comparisons such as >= "standard", min, max and sorting follow that order. Comparisons with < or > on an unordered categorical raise a TypeError.
Q11. You save a DataFrame with categoricals and dates as CSV and as Parquet, then read both back. What differs?
Answer
The CSV version comes back with str for the dates and the categoricals, because CSV stores only text; you must pass parse_dates and dtype again. The Parquet version comes back with the exact dtypes, and equals on the original returns True.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 27 exercises with hints and full solutions, from warm-up to challenge.
- Mini-project: build a churn-risk watch list from the customer file and save it as CSV and Parquet.
- Cheat sheet: every pandas call of this module on one page.
- Next module: 25. pandas advanced teaches groupby, pivot tables, reshaping, merges, window functions and the
.strand.dtaccessors.