The classic Python DataFrame library
pandas
cheat sheet
pandas at a glance: read and write files, inspect, select with loc / iloc, filter, add columns, group by, merge, reshape, strings and dates, missing data, and the pandas 3 changes.
- Version
- v3.1.1
- Snippets
- 111
- Sections
- 11
Version notes · pandas 3.1.1
- 3.1 adds
df.select(…)anddf.filter(mask), both acceptingpd.col(…)expressions (added in 3.0). - 3.1 deprecates
inplace=Trueondrop,rename,sort_values,reset_index,dropna,queryand friends: reassign instead. Needs NumPy 2. - 3.0: Copy-on-Write always.
df["a"][0] = 1(chained assignment) never changesdf: usedf.loc[0, "a"] = 1. - 3.0: text columns default to the
strdtype (notobject), time zones arezoneinfo, andM/Q/Yoffsets areME/QE/YE.
/
Labelled, in-memory tables (DataFrame) and columns (Series) for cleaning, exploring and reshaping data, with readers for nearly every file format.
Works withNumPyPyArrowmatplotlibscikit-learnJupyterSQLAlchemy
Labelled data
index + column labels
Every format
CSV, Excel, Parquet, SQL, JSON
Copy-on-Write
no more SettingWithCopy
In memory
big data? see Polars / DuckDB
Quick start
import pandas as pddf = pd.read_csv("sales.csv", parse_dates=["date"])out = ( df[df["amount"] > 0] .groupby("region", as_index=False) .agg(total=("amount", "sum"), n=("amount", "size")) .sort_values("total", ascending=False))print(out)Read
- Import (
uv add pandas pyarrow) - CSV
- European CSV
- Some columns, forced types
- Parse dates
- Iterate in chunks
- Parquet
- Excel (needs
openpyxl) - JSON Lines
- SQL (SQLAlchemy engine)
Write & create
- CSV without the index
- Parquet
- Excel
- JSON Lines
- Into a database
- From a dict of columns
- From a list of dicts
- To a list of dicts
- First 5 rows (
tail,sample(5)) (rows, columns)- Types, non-null counts, memory
- Column types
- Numeric summary (
include="all"for every column) - Column names
- Frequencies
- Distinct values
- Missing values per column
- Bytes used
- Show every column
- One column →
Series - Several columns →
DataFrame - Same, method style (3.1+)
- Row by index label
- Rows by condition, columns by name
- Row by position
- First 10 rows, first 3 columns
- Single value, fast
- Assign to a selection
- Use a column as the index
- Back to 0, 1, 2…
loc is by label (end inclusive), iloc by position (end exclusive). Assign with one loc[…], never df["a"][i] = ….
- Boolean mask
- And (
|or,~not), parentheses needed - In a list
- Range, inclusive
- String expression,
@for variables - Expression filter (3.1+)
- Sort
- Several keys
- Dedupe
- Top 5 rows
- New column
- In a chain, with
pd.col(3.0+) - In a chain, with a lambda
- If / else (NumPy)
- Bucket values
- Change type
- Parse numbers, bad → NaN
- Rename
- Drop columns
- Map values
- One aggregation →
Series - Named aggregations
- Several keys and functions
- Group total on every row
- Rank within group
- Keep only big groups
- Per month
- Pivot table
- Counts table
- Inner join on a column
- left · right · outer · inner · cross
- Different key names
- Fail on duplicate keys
_mergecolumn: left_only / both…- Stack rows
- Side by side (aligned on index)
- Nearest earlier match
- Long → wide (unique pairs)
- Wide → long
- Column level ↔ index level
- One row per list item
- Transpose
- Nested JSON → flat columns
- True where missing (
notna) - Drop rows with any missing value
- Only check some columns
- Fill per column
- Forward fill (
bfillbackward) - Linear interpolation
- Nullable dtypes (
Int64,boolean…)
Strings: .str
- Case (
upper,title) - Trim
- Substring / regex test
- Regex replace
- Regex group → column
- Split into columns
- Length
Dates: .dt
- Parse
- Parts (
month,day_name(),hour…) - Month periods
- Convert a tz-aware column
- Weekly totals
- Moving average
- Month ends (
ME, notM)
pandas 3 habits v3.0+
Old habitpandas 3
- df.loc[0, "a"] = 1
- df = df.sort_values("a")
- df = df.drop(columns="x")
- df.select("a", "b")
- df.filter(pd.col("a") > 1)
- df.assign(b=pd.col("a") * 2)
- df["s"].dtype == "str"
- pd.date_range(…, freq="ME")
Copy-on-Write means a derived frame never changes its parent, and .copy() is only needed to free memory early.
