Skip to content

24. pandas fundamentals — Cheat sheet

The essentials of module 24 on one page, for pandas 3. Every runnable block on this page is checked against its output.

I want to… Use… Example
import pandas import pandas as pd
make a labeled column pd.Series(values, index=labels) pd.Series([79.99, 249.0], index=["P001", "P002"])
make a table pd.DataFrame(dict_of_lists) pd.DataFrame({"id": ["S01"], "size": [2850]})
read a CSV with dates pd.read_csv(path, parse_dates=[...]) pd.read_csv("data/sales.csv", parse_dates=["order_date"])
read only some columns usecols=[...] usecols=["order_date", "revenue"]
force column dtypes at load dtype={col: dtype} dtype={"region": "category"}
treat extra text as missing na_values=[...] na_values=["-"]
read one Excel sheet pd.read_excel(path, sheet_name=...) pd.read_excel("data/sales_sample.xlsx", sheet_name="sales")
flatten nested JSON pd.json_normalize(records) pd.json_normalize(export["customers"])
one row per nested list item record_path=, meta= json_normalize(recs, record_path="orders", meta=["customer_id"])
read Parquet (some columns) pd.read_parquet(path, columns=[...]) pd.read_parquet("data/sales_sample.parquet")
write without the index to_csv(path, index=False) df.to_parquet("output/x.parquet", index=False)
see the first rows df.head(n) df.head(3)
see random rows, reproducibly df.sample(n, random_state=42) df.sample(5, random_state=42)
see dtypes, gaps and memory df.info() (prints; returns None) df.info()
summary statistics df.describe() df[["price"]].describe()
count values s.value_counts() s.value_counts(normalize=True)
count distinct values s.nunique() df.nunique()
count missing values df.isna().sum()
pick columns df[["a", "b"]] sales[["region", "revenue"]]
pick by labels df.loc[rows, cols] houses.loc["H0003":"H0005", "price"]
pick by positions df.iloc[rows, cols] df.iloc[:5, -1]
one cell, fast df.at[label, col], df.iat[i, j] houses.at["H0003", "price"]
filter rows df[mask] or df.loc[mask, cols] sales[sales["revenue"] > 1000]
combine conditions &, |, ~ with parentheses df[(a > 1) & ~(b == 2)]
value in a list s.isin([...]) s.isin(["North", "East"])
value in a range (inclusive) s.between(lo, hi) s.between("2024-12-01", "2024-12-31")
filter with a string df.query("..."), @var df.query("age >= @min_age and plan == 'premium'")
sort by several columns sort_values([a, b], ascending=[...]) sort_values(["region", "revenue"], ascending=[True, False])
top n rows df.nlargest(n, col) sales.nlargest(5, "revenue")
restore index order df.sort_index()
renumber rows 0..n−1 df.reset_index(drop=True)
add a column df["new"] = expression df["ppsf"] = df["price"] / df["sqft"]
add columns in a chain df.assign(new=lambda d: ...) df.assign(k=lambda d: d["revenue"] / 1000)
if/else per row np.where(cond, a, b) np.where(s >= 500, "large", "small")
several branches np.select(conds, choices, default) np.select([s >= 4, s >= 2], ["high", "mid"], "low")
set some rows of a column df.loc[mask, col] = value df.loc[df["id"] == "S12", "size"] = 1400
look up values s.map(dict_or_series) sales["store_id"].map(city_of)
change a dtype s.astype(dtype) s.astype("int32")
text to numbers, bad → NaN pd.to_numeric(s, errors="coerce")
text to dates pd.to_datetime(s, format=...) pd.to_datetime(s, format="%d/%m/%Y")
save memory on repeated text s.astype("category")
order text values pd.CategoricalDtype([...], ordered=True) ["basic", "standard", "premium"]
compare two frames df1.equals(df2)

Start every pandas script with the display options. They change only what pandas prints:

import numpy as np
import pandas as pd
pd.set_option("display.width", 100) # wrap tables at 100 characters
pd.set_option("display.max_columns", 12) # show up to 12 columns
pd.set_option("display.precision", 3) # show floats with 3 decimals
Option Does
display.max_rows rows shown before pandas cuts the middle (default 60)
display.float_format a function that formats every float, e.g. "{:,.2f}".format
pd.option_context(name, value) a with block that sets an option temporarily
pd.reset_option("all") back to the defaults
prices = pd.Series([79.99, 249.0, 1299.0], index=["P001", "P002", "P003"], name="price")
stores = pd.DataFrame({"store_id": ["S01", "S12"], "size_sqm": [2850, 1350]})
print(prices.index.to_list(), prices.dtype) # labels and dtype
print(stores.shape, stores.columns.to_list()) # (rows, cols) and column names
print(stores.dtypes.astype(str).to_dict()) # one dtype per column
print(stores["size_sqm"].to_numpy()) # values as a NumPy array
Output
['P001', 'P002', 'P003'] float64
(2, 2) ['store_id', 'size_sqm']
{'store_id': 'str', 'size_sqm': 'int64'}
[2850 1350]
Attribute Series DataFrame
.index row labels row labels
.columns — column labels
.dtype / .dtypes one dtype a Series of dtypes
.shape (n,) (n_rows, n_cols)
.to_numpy() 1-D array 2-D array (object if mixed)
.name the Series name —

Arithmetic aligns by label. Labels missing on one side give NaN:

units = pd.Series([2, 1], index=["P003", "P001"])
print((prices * units).to_dict())
Output
{'P001': 79.99, 'P002': nan, 'P003': 2598.0}
Format Read Write Keeps dtypes
CSV pd.read_csv df.to_csv(path, index=False) no
Excel (.xlsx, needs openpyxl) pd.read_excel(path, sheet_name=...) df.to_excel(path, sheet_name=..., index=False) numbers and dates
JSON (flat records) pd.read_json(path) df.to_json(path, orient="records") partly
JSON (nested) pd.json_normalize(records, record_path=, meta=) — partly
Parquet (needs pyarrow) pd.read_parquet(path, columns=[...]) df.to_parquet(path, index=False) yes
read_csv option Does
usecols=[...] load only these columns
parse_dates=[...] parse these columns as dates
dtype={col: type} set dtypes: "category", "int32", "Int64", "str"
na_values=[...] extra missing-value tokens ("" and "N/A" are already included)
keep_default_na=False keep empty cells as "" instead of NaN
index_col="col" use a column as the index
nrows=1000 read only the first rows
encoding="latin-1" non-UTF-8 files
from pathlib import Path
Path("output").mkdir(exist_ok=True) # never write into data/
sample = pd.read_parquet("data/sales_sample.parquet", columns=["order_date", "revenue"])
sample.to_csv("output/sample.csv", index=False)
print(pd.read_csv("output/sample.csv").dtypes.astype(str).to_dict()) # date lost
print(sample.dtypes.astype(str).to_dict())
Output
{'order_date': 'str', 'revenue': 'float64'}
{'order_date': 'datetime64[us]', 'revenue': 'float64'}
Call Shows
df.head(n), df.tail(n) first or last n rows (default 5)
df.sample(n, random_state=42) n random rows, the same on every run
df.shape, len(df) size
df.info() dtypes, non-null counts, memory; prints by itself
df.describe() count, mean, std, min, quartiles, max of numeric columns
df.describe(include="str") count, unique, top, freq of text columns
s.value_counts(normalize=True, dropna=False) shares, with NaN counted
s.unique(), s.nunique() distinct values, their number
df.isna().sum() missing values per column
df.memory_usage(deep=True) bytes per column, text included
houses = pd.read_csv("data/houses.csv", index_col="house_id", parse_dates=["sold_date"])
print(houses.shape)
print(houses["neighborhood"].value_counts().head(3).to_dict())
missing = houses.isna().sum()
print(missing[missing > 0].to_dict()) # only the columns with gaps
Output
(3000, 13)
{'Maple Grove': 454, 'Westfield': 450, 'Cedar Park': 407}
{'lot_sqft': 90, 'school_rating': 90}
Syntax By Returns Slice end
df["col"] column name Series —
df[["a", "b"]] column names DataFrame —
df.loc["r1":"r3", "a":"c"] labels DataFrame included
df.iloc[0:3, 0:2] positions DataFrame excluded
df.loc[mask, ["a"]] mask + labels DataFrame —
df.at["r1", "a"], df.iat[0, 0] one cell scalar —
df.query("a > 1 and b == 'x'") expression DataFrame —
print(houses.loc["H0003":"H0004", ["neighborhood", "price"]]) # end label included
print(houses.iloc[2:4, [0, -1]].index.to_list()) # end position excluded
print(houses.at["H0003", "price"]) # one cell
Output
neighborhood price
house_id
H0003 Cedar Park 223000
H0004 Downtown 431000
['H0003', 'H0004']
223000
big = houses["sqft"] >= 3000
lake_or_oak = houses["neighborhood"].isin(["Lakeview", "Oak Hill"])
recent = houses["sold_date"].between("2024-01-01", "2024-12-31")
print((big & lake_or_oak).sum(), (big | lake_or_oak).sum(), (~big).sum())
print(len(houses[big & lake_or_oak & recent]))
min_rating = 9
print(len(houses.query("school_rating >= @min_rating and has_pool == 1")))
Output
120 788 2779
42
121
Need Write
and / or / not (a) & (b), (a) | (b), ~(a)
equals one of several values s.isin(["x", "y"])
range, both ends included s.between(lo, hi); inclusive="left" for lo <= s < hi
missing / present s.isna(), s.notna()
share of rows that match mask.mean()
count of rows that match mask.sum()
ranked = houses.sort_values(["neighborhood", "price"], ascending=[True, False])
print(ranked[["neighborhood", "price"]].head(2))
print(houses.nsmallest(2, "price")["price"].to_list())
Output
neighborhood price
house_id
H0914 Cedar Park 719500
H2715 Cedar Park 615500
[117500, 120000]
Option Does
ascending=[True, False] one direction per key
na_position="first" missing values first (default last)
kind="stable" ties keep their original order
ignore_index=True result gets a fresh 0..n−1 index
key=func sort by a transformed value, e.g. key=lambda s: s.str.lower()
houses["price_per_sqft"] = houses["price"] / houses["sqft"] # vectorized arithmetic
houses["size_class"] = np.where(houses["sqft"] >= 2500, "large", "standard")
houses["top_school"] = False # default first ...
houses.loc[houses["school_rating"] >= 8, "top_school"] = True # ... then some rows
extra = houses.assign(price_k=lambda d: d["price"] / 1000) # a new frame
print(houses[["price_per_sqft", "size_class", "top_school"]].head(2))
print("price_k" in houses.columns, "price_k" in extra.columns)
Output
price_per_sqft size_class top_school
house_id
H0001 453.512 standard True
H0002 302.174 standard True
False True
Task Fast Slow
arithmetic on columns df["a"] * df["b"] df.apply(lambda r: r["a"] * r["b"], axis=1)
if/else np.where(cond, x, y) s.apply(lambda v: x if v > 0 else y)
several branches np.select(conds, choices, default) a row function with if/elif
code → label lookup s.map(dict_or_series) s.apply(lambda v: mapping[v])
rounding s.round(2) s.apply(round, args=(2,))
any NumPy math np.log(s), np.sqrt(s) s.apply(math.log)

apply(axis=1) makes one Python call per row; vectorized code makes one compiled loop per column. On 20,000 rows, vectorized code is often 100 times faster or more; the factor depends on the machine.

dtype Missing marker Note
int64 — a blank cell turns the column into float64
Int64 <NA> nullable integers
float64 NaN
float32 NaN half the memory, about 7 significant digits
bool —
str NaN the pandas 3 default for text (Arrow-backed)
datetime64[us] NaT from parse_dates or pd.to_datetime
category NaN codes plus categories
object None/NaN lists, dicts, mixed values
raw = pd.Series(["79.99", "1,299.00", "n/a", "-"])
clean = pd.to_numeric(raw.str.replace(",", ""), errors="coerce") # bad -> NaN
print(clean.to_list(), clean.isna().sum())
dates = pd.to_datetime(pd.Series(["07/01/2023", "31/12/2024"]), format="%d/%m/%Y")
print(dates.dt.strftime("%Y-%m-%d").to_list())
print(pd.Series([3, None, 5], dtype="Int64").to_list())
Output
[79.99, 1299.0, nan, nan] 2
['2023-01-07', '2024-12-31']
[3, <NA>, 5]
Tool On a bad value
s.astype("float64") raises ValueError
pd.to_numeric(s, errors="coerce") NaN
pd.to_numeric(s, downcast="integer") picks the smallest integer dtype that fits
pd.to_datetime(s, format="%Y-%m-%d", errors="coerce") NaT
df.astype({"a": "int32", "b": "category"}) several columns at once
df.select_dtypes(include="number") select columns by dtype ("str", "category", "datetime")
customers = pd.read_csv("data/customers.csv", usecols=["customer_id", "plan"])
print(customers["plan"].memory_usage(deep=True), "bytes as str")
plan_type = pd.CategoricalDtype(["basic", "standard", "premium"], ordered=True)
customers["plan"] = customers["plan"].astype(plan_type)
print(customers["plan"].memory_usage(deep=True), "bytes as category")
print((customers["plan"] >= "standard").sum(), customers["plan"].max())
print(customers["plan"].cat.codes.head(3).to_list())
Output
73058 bytes as str
5284 bytes as category
2972 premium
[2, 1, 2]
Call Does
s.astype("category") unordered, categories sorted alphabetically
pd.CategoricalDtype(cats, ordered=True) fixed categories in your order
s.cat.categories, s.cat.codes the distinct values, the integer code per row
s.cat.add_categories([...]) allow a new value
s.cat.remove_unused_categories() drop categories that no row uses
s.value_counts(sort=False) counts in category order
s.astype("str") back to text
Topic pandas 3 Old habit to drop
text dtype str (Arrow-backed) expecting object for text
copy-on-write always on: every selection behaves as a copy df["a"][mask] = v (does nothing, warns)
setting values df.loc[mask, "a"] = v chained assignment
inplace=True deprecated on most methods (sort_values, dropna, drop, rename, set_index, reset_index, query…): Pandas4Warning assign the result: df = df.sort_values("a")
values as array .to_numpy() .values (a pandas array for text)
datetime unit datetime64[us] by default expecting datetime64[ns]
element-wise on a frame df.map(func) df.applymap(func) (removed)
  • and, or, not on a Series raise ValueError: The truth value of a Series is ambiguous. Use &, |, ~.
  • & binds before ==: write (a == 1) & (b > 2), with parentheses.
  • df["col"][mask] = value changes nothing under copy-on-write. Use df.loc[mask, "col"] = value.
  • loc slices include the end label; iloc slices exclude the end position.
  • After a filter or sort, labels and positions differ. iloc[0] is the first row now, not the row labeled 0.
  • print(df.info()) prints an extra None. Call df.info() alone.
  • to_csv without index=False adds an Unnamed: 0 column on the next read.
  • CSV forgets dtypes: dates and categoricals come back as str. Parquet keeps them.
  • An integer column with one blank loads as float64. Use "Int64" if you need integers with gaps.
  • loc[mask, "new_col"] = v on a new column fills the other rows with NaN. Create the column with a default first.
  • errors="coerce" turns bad values into NaN silently. Count isna() before and after.
  • pd.to_datetime(s, format="mixed", dayfirst=True) also reads ISO dates as year-day-month. Parse each known format explicitly.
  • s.map(dict) gives NaN for keys missing from the dict.
  • >= on an unordered categorical raises TypeError. Use an ordered CategoricalDtype.
  • category on an id column wastes memory. Use it for few distinct, repeated values.
  • True + True on boolean Series is a logical or (True), not 2. Multiply one side by an integer or call .astype(int) before adding flags.