Connect any database. Ask in plain English.

Try free
← Blog

Pandas Cheat Sheet: 36 Snippets Run on pandas 3.1.2, and the apply That Was 1,600x Slower (2026)

The pandas you keep looking up, run on pandas 3.1.2 against 4,734 invented orders with the output it printed: reading and writing, loc, iloc and query, groupby with named aggregation, pivot_table, merge, dates, strings, missing values and the code pandas 3 broke. A row-wise apply took 7.9 seconds on 473,400 rows where np.where took 4.8 ms, and pandas 3's string dtype held the sample in 618 KB instead of 1,755 KB.

Fastero Dev TeamFastero Dev Team2026-12-03

We installed pandas 3.1.2, the release of 30 November 2026, in a fresh virtual environment on Python 3.14.3, and ran every snippet on this page against one file: 4,734 invented orders from November 2024 to October 2026, the sample every new Fastero account starts with. Each output is what pandas printed, with long lines wrapped and anything trimmed marked as such. We also timed four ways to add a computed column and measured the sample's memory under six choices of dtype.

The short answer: the pandas people look up most is pd.read_csv(path, parse_dates=[...]) to read, df.info() to inspect, df.loc[rows, cols] by label and df.iloc[rows, cols] by position, df[(cond1) & (cond2)] or df.query(...) to filter, df.groupby(key).agg(new=("col", "sum")) for named aggregation, then pivot_table, merge, .dt for dates and .str for text. The current release is 3.1.2 and needs Python 3.11 or newer. Pandas 3 stores text as a str dtype, makes every selection behave as a copy, and removed resample("M"), applymap and fillna(method=...). Checked 3 December 2026.

Fastero

Connect your database. Ask questions. Get dashboards.

Postgres, BigQuery, Snowflake, and 10+ sources — live-connected, AI-powered, no dashboard builder learning curve.

Try free →

The pandas cheat sheet in one table

Patterns with placeholder names: df is a DataFrame, s a Series. The sections that follow run each one on the sample with pandas 3.1.2.

Task pandas 3 code Note
Read a CSV pd.read_csv("f.csv", parse_dates=["d"]) Text columns arrive as str
Read Excel or Parquet pd.read_excel("f.xlsx"), pd.read_parquet("f.parquet") Needs openpyxl or pyarrow
Read from a database pd.read_sql(query, con) SQLAlchemy, ADBC or sqlite3
Write df.to_csv("f.csv", index=False) Also to_parquet, to_excel, to_sql
Size, types, nulls df.shape, df.info() df.isna().sum() counts gaps
Summary statistics df.describe() Numeric columns only by default
Count each value s.value_counts() Sorted, most common first
Pick columns df[["a", "b"]] or df.select("a", "b") select is new in 3.1
Rows and columns by label df.loc[df["a"] > 1, ["a", "b"]] Slices include the end label
Rows and columns by position df.iloc[:5, [0, 2]] Slices exclude the end
Filter on two conditions df[(df["a"] > 1) & (df["b"] == "x")] &, |, ~, each in parentheses
Filter with a string df.query("a > 1 and b == 'x'") @name reads a Python variable
New column df.assign(c=pd.col("a") * 2) pd.col is new in 3.0
If/else column np.where(df["q"] >= 5, "bulk", "single") Vectorised, no apply
Sort df.sort_values("a", ascending=False) df.nlargest(3, "a") for a top 3
Total per group df.groupby("k")["v"].sum() Keys become the index
Several named results df.groupby("k").agg(n=("v", "count")) as_index=False for a flat table
Pivot df.pivot_table("v", index="r", columns="c") Default aggfunc is the mean
Wide to long df.melt(id_vars="k") The reverse of a pivot
Join on a key a.merge(b, on="k", how="left") validate= catches duplicate keys
Stack tables pd.concat([a, b], ignore_index=True) Same columns, more rows
Parse dates pd.to_datetime(s, format="%d/%m/%Y") errors="coerce" turns junk into NaT
Date parts s.dt.year, s.dt.day_of_week dayofweek is deprecated in 3.1
Monthly totals df.resample("ME", on="d")["v"].sum() "M" raises in pandas 3
Text s.str.upper(), s.str.contains("x") Works on the str dtype
Fill gaps s.fillna(0), s.ffill() fillna(method=...) is gone

Install pandas and check the version

python -m venv venv
venv/Scripts/python -m pip install pandas pyarrow openpyxl

That's Windows; on a Mac or Linux the interpreter is venv/bin/python.

import numpy as np
import pandas as pd
 
print(pd.__version__, np.__version__)
3.1.2 2.5.5

Pandas 3.0 and 3.1 need Python 3.11 or newer, and 3.1 needs NumPy 2.0.2 or newer, per the release notes and PyPI. PyArrow is optional, but install it: without it, text columns fall back to Python objects (nearly three times the memory on the sample, measured further down), and read_parquet needs it now that 3.1 has deprecated the other engine, fastparquet. Every snippet that follows shares one session, so a column added in one block exists in the next.

Read and write CSV, Excel, Parquet and SQL

df = pd.read_csv("sample-sales.csv", parse_dates=["order_date"])
df.head(3)
   order_id order_date region  ...  quantity  unit_price  revenue
0     10001 2024-11-01  North  ...         4      170.07   680.28
1     10002 2024-11-01  North  ...         1      903.73   903.73
2     10003 2024-11-01   West  ...         3       63.56   190.68
 
[3 rows x 10 columns]

Read only the columns you need and set their types as you read; on a big file this is where memory is won, as our read large CSV guide measures:

small = pd.read_csv("sample-sales.csv", usecols=["order_date", "region", "revenue"],
                    dtype={"region": "category"}, parse_dates=["order_date"])
small.dtypes
order_date    datetime64[us]
region              category
revenue              float64
dtype: object

Writing is the same verbs with to_. The same 4,734 rows took 377 KB as CSV, 228 KB as Excel and 102 KB as Parquet, and Parquet and Excel both kept the date type on the way back in:

import os
 
df.to_csv("sales-copy.csv", index=False)
df.to_parquet("sales.parquet")            # needs pyarrow
df.to_excel("sales.xlsx", index=False)    # needs openpyxl
 
for f in ["sales-copy.csv", "sales.parquet", "sales.xlsx"]:
    print(f"{f:15} {os.path.getsize(f) / 1024:6.0f} KB")
 
back = pd.read_parquet("sales.parquet")
xl = pd.read_excel("sales.xlsx", sheet_name=0)
print(back["order_date"].dtype, xl["order_date"].dtype, xl.shape)
sales-copy.csv     377 KB
sales.parquet      102 KB
sales.xlsx         228 KB
datetime64[us] datetime64[us] (4734, 10)

For SQL, to_sql writes a table and read_sql runs a query. Pass values with params rather than pasting them into the string:

import sqlite3
 
con = sqlite3.connect("sales.db")
df.to_sql("sales", con, if_exists="replace", index=False)
 
q = """
SELECT region, ROUND(SUM(revenue), 2) AS revenue
FROM sales
WHERE channel = ?
GROUP BY region
ORDER BY revenue DESC
"""
pd.read_sql(q, con, params=("Online",))
  region    revenue
0  North  213296.95
1   West  201271.42
2   East  151487.88
3  South  142073.15

SQLite has no date type, so dates come back as text unless you ask: pd.read_sql(..., parse_dates=["order_date"]) turned str into datetime64[us] in our run. The pandas docs list what con accepts: an ADBC connection, a SQLAlchemy connectable, a URI string or a sqlite3 connection, and "If a DBAPI2 object, only sqlite3 is supported." For Postgres, pass a SQLAlchemy engine (not run here, it needs a server):

from sqlalchemy import create_engine
 
engine = create_engine("postgresql+psycopg2://user:password@host:5432/dbname")
orders = pd.read_sql("SELECT * FROM sales WHERE order_date >= '2026-01-01'", engine)

Inspect a DataFrame

df.info()
<class 'pandas.DataFrame'>
RangeIndex: 4734 entries, 0 to 4733
Data columns (total 10 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   order_id    4734 non-null   int64
 1   order_date  4734 non-null   datetime64[us]
 2   region      4734 non-null   str
 3   channel     4734 non-null   str
 4   segment     4734 non-null   str
 5   category    4734 non-null   str
 6   product     4734 non-null   str
 7   quantity    4734 non-null   int64
 8   unit_price  4734 non-null   float64
 9   revenue     4734 non-null   float64
dtypes: datetime64[us](1), float64(2), int64(2), str(5)
memory usage: 571.7 KB

Two pandas 3 details show here: text columns are str, not object, and parsed dates are datetime64[us] (microseconds), not nanoseconds.

print(df.shape)
print(df["region"].value_counts())
print(df[["quantity", "unit_price", "revenue"]].describe().round(2))
(4734, 10)
region
West     1371
North    1310
East     1082
South     971
Name: count, dtype: int64
       quantity  unit_price  revenue
count   4734.00     4734.00  4734.00
mean       3.74      138.07   311.30
std        2.97      175.37   335.34
min        1.00       11.04    11.07
25%        1.00       24.80   100.26
50%        3.00       63.83   192.82
75%        4.00      186.92   357.98
max       12.00      971.22  1811.00

Select rows and columns with loc, iloc and query

loc takes labels and boolean masks, iloc takes integer positions:

df.loc[df["region"] == "West", ["order_id", "product", "revenue"]].head(3)
    order_id        product  revenue
2      10003   Starter plan   190.68
17     10018  Standing desk   431.93
22     10023   Office chair   249.18
df.iloc[:3, [0, 2, -1]]       # first 3 rows; 1st, 3rd and last columns
   order_id region  revenue
0     10001  North   680.28
1     10002  North   903.73
2     10003   West   190.68

query reads like SQL, and @ pulls in a Python variable:

min_rev = 1800
df.query("region == 'West' and revenue > @min_rev")[["order_id", "product", "revenue"]]
      order_id        product  revenue
2702     12703  Standing desk  1806.48
3173     13174  Standing desk  1806.48
4120     14121  Standing desk  1808.60
4339     14340  Standing desk  1801.80

Pandas 3.1 added DataFrame.select, which picks columns and can compute new ones in the same call:

df.select("order_id", "region", rev_k=pd.col("revenue") / 1000).head(3)   # pandas 3.1+
   order_id region    rev_k
0     10001  North  0.68028
1     10002  North  0.90373
2     10003   West  0.19068

Filter rows in pandas

Combine conditions with & (and), | (or) and ~ (not), each condition in parentheses:

big_online = df[(df["revenue"] > 1000) & (df["channel"] == "Online")]
east_west = df[df["region"].isin(["East", "West"])]
q1_2026 = df[df["order_date"].between("2026-01-01", "2026-03-31")]
plans = df[df["product"].str.contains("plan", case=False)]
not_partner = df[~(df["channel"] == "Partner")]
print(len(big_online), len(east_west), len(q1_2026), len(plans), len(not_partner))
114 2453 539 898 3761

Python's and doesn't work on a whole column:

df[df["revenue"] > 1000 and df["channel"] == "Online"]
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.item(), a.any() or
a.all().

In pandas 3.1, filter also takes a condition, which reads well at the end of a chain:

df.filter(pd.col("revenue") > 1806.5)[["order_id", "region", "revenue"]]   # pandas 3.1+
      order_id region  revenue
1011     11012   East  1809.48
1956     11957  South  1811.00
3829     13830  South  1806.56
4120     14121   West  1808.60

Add a new column

df = df.assign(
    net=pd.col("revenue") * 0.9,                       # pandas 3.0+
    size=np.where(df["quantity"] >= 5, "bulk", "single"),
    margin=lambda d: d["revenue"] - d["net"],          # works on any version
)
df["month"] = df["order_date"].dt.to_period("M")
df.loc[df["channel"] == "Partner", "commission"] = df["revenue"] * 0.1
df[["revenue", "net", "size", "month", "commission"]].head(3)
   revenue      net    size    month  commission
0   680.28  612.252  single  2024-11      68.028
1   903.73  813.357  single  2024-11         NaN
2   190.68  171.612  single  2024-11         NaN

pd.col("revenue") replaces lambda d: d["revenue"] and arrived in pandas 3.0, so keep the lambda if the code must also run on 2.x. Setting a new column through loc with a mask fills the other rows with NaN. Note that to_period("M") still takes "M": a period is a month, while resample wants "ME" for month end.

Sort a DataFrame

print(df.sort_values(["region", "revenue"], ascending=[True, False])
        [["region", "product", "revenue"]].head(3))
print(df.nlargest(3, "revenue")[["order_id", "product", "revenue"]])
     region        product  revenue
1011   East  Standing desk  1809.48
2611   East  Standing desk  1761.32
4384   East  Standing desk  1761.00
      order_id        product  revenue
1956     11957  Standing desk  1811.00
1011     11012  Standing desk  1809.48
4120     14121  Standing desk  1808.60

groupby and agg, with named aggregation

df.groupby("region")["revenue"].sum()
region
East     336183.61
North    417482.48
South    306511.46
West     413523.32
Name: revenue, dtype: float64

Named aggregation, new_name=("column", "function"), returns several results with names you chose:

(df.groupby(["region", "channel"], as_index=False)
   .agg(orders=("order_id", "count"),
        revenue=("revenue", "sum"),
        avg_order=("revenue", "mean"),
        products=("product", "nunique"))
   .round(1)
   .head(4))
  region     channel  orders   revenue  avg_order  products
0   East      Online     501  151487.9      302.4        13
1   East     Partner     230   64769.2      281.6        13
2   East  Sales team     351  119926.5      341.7        13
3  North      Online     660  213297.0      323.2        13

transform puts a group's number back on every row, here each order's share of its region:

df["region_share"] = df["revenue"] / df.groupby("region")["revenue"].transform("sum")
df[["region", "revenue", "region_share"]].head(3)
  region  revenue  region_share
0  North   680.28      0.001629
1  North   903.73      0.002165
2   West   190.68      0.000461

Twelve more patterns, from pd.Grouper to top N per group, are in our pandas groupby guide.

pivot_table and melt

pt = df.pivot_table(index="region", columns="channel", values="revenue",
                    aggfunc="sum", margins=True, margins_name="Total").round(0)
pt
channel    Online   Partner  Sales team      Total
region
East     151488.0   64769.0    119927.0   336184.0
North    213297.0   88855.0    115330.0   417482.0
South    142073.0   67118.0     97320.0   306511.0
West     201271.0   83592.0    128660.0   413523.0
Total    708129.0  304335.0    461237.0  1473701.0

Leave out aggfunc and you get the mean, not the sum. melt goes back from wide to long:

wide = pt.drop(index="Total", columns="Total").reset_index()
long = wide.melt(id_vars="region", var_name="channel", value_name="revenue")
print(long.shape)
long.head(4)
(12, 3)
  region channel   revenue
0   East  Online  151488.0
1  North  Online  213297.0
2  South  Online  142073.0
3   West  Online  201271.0

Margins, fill_value, crosstab and why pivot raises on duplicates: pandas pivot table.

merge, join and concat

merge joins on columns. validate raises if a key you expect to be unique isn't, and indicator shows where each row came from:

targets = pd.DataFrame({"region": ["East", "North", "South", "West", "Central"],
                        "target": [350_000, 400_000, 300_000, 420_000, 50_000]})
by_region = df.groupby("region", as_index=False)["revenue"].sum()
by_region.merge(targets, on="region", how="outer", validate="one_to_one",
                indicator=True).round(0)
    region   revenue  target      _merge
0  Central       NaN   50000  right_only
1     East  336184.0  350000        both
2    North  417482.0  400000        both
3    South  306511.0  300000        both
4     West  413523.0  420000        both

join matches on the index, and concat stacks frames:

joined = by_region.set_index("region").join(targets.set_index("region"), how="inner")
y2025 = df[df["order_date"].dt.year == 2025]
y2026 = df[df["order_date"].dt.year == 2026]
both = pd.concat([y2025, y2026], ignore_index=True)
print(joined.shape, len(y2025), len(y2026), len(both))
(4, 2) 2187 2253 4440

Every how=, merging on several columns and the mistakes that multiply rows are in pandas merge.

Connect any database. Ask in plain English.

Start free →

Dates: to_datetime, the .dt accessor and resample

d = df["order_date"].iloc[[0, 2000, 4733]]
pd.DataFrame({"date": d, "year": d.dt.year, "quarter": d.dt.quarter,
              "month": d.dt.month_name(), "weekday": d.dt.day_name(),
              "dow": d.dt.day_of_week, "week": d.dt.isocalendar().week})
           date  year  quarter     month   weekday  dow  week
0    2024-11-01  2024        4  November    Friday    4    44
2000 2025-10-11  2025        4   October  Saturday    5    41
4733 2026-10-31  2026        4   October  Saturday    5    44

Give to_datetime a format when you know it, and errors="coerce" to turn bad values into NaT instead of raising:

s = pd.Series(["03/12/2026", "31/12/2026", "not a date"])
print(pd.to_datetime(s, format="%d/%m/%Y", errors="coerce"))
0   2026-12-03
1   2026-12-31
2          NaT
dtype: datetime64[us]

Be careful with format="mixed" and dayfirst=True: it read the ISO date 2026-12-03 as 12 March.

pd.to_datetime(pd.Series(["2026-12-03", "04/12/2026"]), format="mixed", dayfirst=True)
0   2026-03-12
1   2026-12-04
dtype: datetime64[us]

resample groups by time. Pandas 3 accepts only the new aliases, ME for month end, QS for quarter start, h for hours and min for minutes:

monthly = df.resample("ME", on="order_date")["revenue"].sum()   # month end
print(monthly.tail(3))
print(df.resample("QS", on="order_date")["order_id"].count().tail(3))   # quarter start
order_date
2026-08-31    87202.49
2026-09-30    64819.38
2026-10-31    57517.58
Freq: ME, Name: revenue, dtype: float64
order_date
2026-04-01    766
2026-07-01    746
2026-10-01    202
Freq: QS-JAN, Name: order_id, dtype: int64

The old "M" now fails:

ValueError: Invalid frequency: M. Failed to parse with error message:
ValueError("'M' is no longer supported for offsets. Please use 'ME' instead.")

Strings: the .str accessor

p = df["product"]
pd.DataFrame({"product": p, "upper": p.str.upper(), "len": p.str.len(),
              "first_word": p.str.split().str[0],
              "plan": p.str.contains("plan"),
              "swapped": p.str.replace("plan", "tier")}).drop_duplicates().head(4)
        product         upper  len first_word   plan       swapped
0     Team plan     TEAM PLAN    9       Team   True     Team tier
1  Training day  TRAINING DAY   12   Training  False  Training day
2  Starter plan  STARTER PLAN   12    Starter   True  Starter tier
3  Notebook set  NOTEBOOK SET   12   Notebook  False  Notebook set

str.extract with named groups splits text into columns, and a missing value stays missing:

codes = pd.Series(["  ab-101 ", "CD-202", None, "ef-3x3"])
print(codes.str.strip().str.upper())
print(codes.str.extract(r"(?P<letters>[a-zA-Z]+)-(?P<num>\d+)"))
print(codes.dtype)
0    AB-101
1    CD-202
2       NaN
3    EF-3X3
dtype: str
  letters  num
0      ab  101
1      CD  202
2     NaN  NaN
3      ef    3
str

Missing values

The commission column from earlier is empty for every order not sold by a partner:

print(df[["commission", "revenue"]].isna().sum())
filled = df["commission"].fillna(0)
kept = df.dropna(subset=["commission"])
print(filled.isna().sum(), len(kept))
commission    3761
revenue          0
dtype: int64
0 973
s = pd.Series([1.0, None, None, 4.0])
pd.DataFrame({"s": s, "ffill": s.ffill(), "bfill": s.bfill(),
              "interpolate": s.interpolate(), "mean": s.fillna(s.mean())})
     s  ffill  bfill  interpolate  mean
0  1.0    1.0    1.0          1.0   1.0
1  NaN    1.0    4.0          2.0   2.5
2  NaN    1.0    4.0          3.0   2.5
3  4.0    4.0    4.0          4.0   4.0

fillna(method="ffill") was removed in pandas 3 and now raises:

TypeError: NDFrame.fillna() got an unexpected keyword argument 'method'

Method chaining

Each step returns a new DataFrame, so a whole analysis can read top to bottom with no temporary names:

top_months = (
    pd.read_csv("sample-sales.csv", parse_dates=["order_date"])
    .query("channel == 'Online'")
    .assign(month=pd.col("order_date").dt.to_period("M"))
    .groupby("month", as_index=False)["revenue"].sum()
    .sort_values("revenue", ascending=False)
    .head(3)
)
top_months
      month   revenue
20  2026-07  42573.78
21  2026-08  42460.16
19  2026-06  41481.89

pipe drops your own function into the chain:

def add_margin(d, rate):
    return d.assign(margin=d["revenue"] * rate)
 
(df.pipe(add_margin, rate=0.3)
   .groupby("category")["margin"].sum()
   .round(0))
category
Hardware    211303.0
Services     59006.0
Software    112290.0
Supplies     59512.0
Name: margin, dtype: float64

Is apply slow in pandas? apply vs vectorised vs NumPy

We computed one column four ways, 10% off orders of five units or more, and checked that all four gave the same numbers:

def row_apply(df):
    def net(r):
        return r["revenue"] * 0.9 if r["quantity"] >= 5 else r["revenue"]
    return df.apply(net, axis=1)
 
def list_comp(df):
    vals = [r * 0.9 if q >= 5 else r for q, r in zip(df["quantity"], df["revenue"])]
    return pd.Series(vals, index=df.index)
 
def pandas_where(df):
    return df["revenue"].where(df["quantity"] < 5, df["revenue"] * 0.9)
 
def numpy_where(df):
    q, r = df["quantity"].to_numpy(), df["revenue"].to_numpy()
    return np.where(q >= 5, r * 0.9, r)

On the sample and on the sample repeated 100 times, timed with time.perf_counter, garbage collection off, the methods interleaved and the median taken:

   4,734 rows  df.apply(axis=1)             median     59.233 ms  (n=45)
   4,734 rows  list comprehension           median      1.754 ms  (n=300)
   4,734 rows  Series.where (vectorised)    median      0.491 ms  (n=300)
   4,734 rows  np.where on arrays           median      0.074 ms  (n=300)
 473,400 rows  df.apply(axis=1)             median   7917.226 ms  (n=5)
 473,400 rows  list comprehension           median    282.484 ms  (n=15)
 473,400 rows  Series.where (vectorised)    median      7.413 ms  (n=50)
 473,400 rows  np.where on arrays           median      4.831 ms  (n=50)

Bar chart on a log scale of the median time to add one computed column: df.apply with axis=1 took 59 ms on 4,734 rows and 7.9 s on 473,400 rows, a list comprehension 1.8 ms and 282 ms, Series.where 0.49 ms and 7.4 ms, and np.where 0.07 ms and 4.8 ms

Median time to add one computed column, measured 3 December 2026 on pandas 3.1.2, NumPy 2.5.5 and Python 3.14.3 on an Intel i7-11800H laptop.

A row-wise apply builds a Series for every row, so it was 800 times slower than np.where on the sample and 1,600 times slower on 473,400 rows, where it took 7.9 seconds against 4.8 ms. A list comprehension sat in between. At the larger size, pandas' own where took about one and a half times as long as raw NumPy, so dropping to NumPy matters most on small frames run many times. The laptop was shared, and across four runs the sample's apply took 59 to 104 ms and the large one 5.2 to 7.9 seconds, but the order of the four never changed. The rule holds: write a column as arithmetic on whole columns, and reach for apply last.

How to reduce pandas memory: default, category and string dtypes

text = ["region", "channel", "segment", "category", "product"]
default = pd.read_csv("sample-sales.csv")
compact = pd.read_csv("sample-sales.csv", parse_dates=["order_date"],
                      dtype={c: "category" for c in text})
for name, d in [("default", default), ("compact", compact)]:
    print(f"{name:8} {d.memory_usage(deep=True).sum() / 1024:6.0f} KB")
print(compact.groupby("region")["revenue"].sum().round(2).tolist())
default     618 KB
compact     210 KB
[336183.61, 417482.48, 306511.46, 413523.32]

Bar chart of the sample's memory by dtype: text as object, the pandas 2 default, 1,755 KB; str without pyarrow 1,755 KB; str with pyarrow, the pandas 3 default, 618 KB; dtype_backend pyarrow 461 KB; text as category with dates parsed 210 KB; category, dates and 32-bit numbers 122 KB

memory_usage(deep=True) of the 4,734-row sample under six dtype choices, measured 3 December 2026 on pandas 3.1.2 with pyarrow 26.0.1. The CSV is 374 KB on disk.

Pandas 3's default str dtype, backed by PyArrow, held the sample in 618 KB where pandas 2's object columns took 1,755 KB. With Python storage, which is what str falls back to without PyArrow, it took exactly as much as object. The five text columns hold only 3 to 13 distinct values each, so as category they shrank from 387 KB to 25 KB, and the whole frame to 210 KB with the same totals per region. Downcasting the numbers to int32 and float32 reached 122 KB, but float32 moved region totals by about a cent, so keep money in float64. Category suits columns with few distinct values; the 4,734 unique order IDs took 46 KB as a category against 37 KB as int64. For files larger than memory, see read large CSV.

What pandas 3 changed: the gotchas

Pandas 3.0 (21 January 2026) and 3.1 (22 October 2026) changed or removed code you'll still find in older tutorials. Each row ran on 3.1.2:

Old code What pandas 3.1.2 does Write instead
df[mask]["col"] = 0 Warns ChainedAssignmentError, changes nothing df.loc[mask, "col"] = 0
s.dtype == object for text False: the dtype is str pd.api.types.is_string_dtype(s)
df.select_dtypes("object") Pandas4Warning, still includes str df.select_dtypes("str")
resample("M"), "H", "T" ValueError "ME", "h", "min"
df.applymap(f) AttributeError df.map(f)
s.fillna(method="ffill") TypeError s.ffill()
sort_values(..., inplace=True) Pandas4Warning since 3.1 df = df.sort_values(...)
s.dt.dayofweek Pandas4Warning since 3.1 s.dt.day_of_week
a.join(b, lsuffix=, rsuffix=) Pandas4Warning since 3.1 a.join(b, suffixes=("_l", "_r"))
dates.astype("int64") Microseconds, 1,000 times smaller than before .dt.as_unit("ns") first
s[0] on an integer index The label 0, never the position s.iloc[0]
Grouping by a category Empty categories left out groupby(..., observed=False)
Putting a number in a str column TypeError Convert it to a string first

Two changes cause most of these. Copy-on-Write is the only mode: in the 3.0 notes' words, "any subset or returned series/dataframe always behaves as a copy of the original, and thus never modifies the original." So chained assignment never works, SettingWithCopyWarning is gone, and defensive .copy() calls are no longer needed. We ran it:

west = df[df["region"] == "West"]
west["revenue"] = 0                        # changes west only, no warning
df[df["region"] == "West"]["revenue"] = 0  # chained: changes nothing
print(df.loc[df["region"] == "West", "revenue"].sum().round(2))
 
fixed = df.copy()
fixed.loc[fixed["region"] == "West", "revenue"] = 0   # one step: works
print(fixed.loc[fixed["region"] == "West", "revenue"].sum())
ChainedAssignmentError: A value is being set on a copy of a DataFrame or Series through
chained assignment. (three more lines trimmed)
413523.32
0.0

The default string dtype means text columns are str, can hold only strings or missing values, and use NaN for missing. The inplace deprecation in 3.1 follows from Copy-on-Write: the 3.1 notes call it "essentially syntactic sugar for reassigning the result", so reassigning costs nothing extra. Our pandas 3 guide covers the upgrade in depth.

Run these snippets in a Fastero notebook

Fastero is an AI and data platform where people and AI agents work together on a team's data, in the browser. Its notebooks run Python 3.11 with pandas (and so NumPy), DuckDB, SQLAlchemy, openpyxl, seaborn and plotly preinstalled; we don't promise a pandas version, so run pd.__version__ first: pd.col needs pandas 3.0, and select and filter with a condition need 3.1. Every new account has the same invented sales table used on this page, which a SQL cell can query and hand to Python as a pandas DataFrame. You can also upload a CSV or Excel file (up to 100 MB) and read it in a notebook by its path.

A Fastero notebook in a demo workspace: one pandas cell builds a DataFrame of twelve invented solar sites inline, computes output against forecast and sorts the sites, with the table printed below

A pandas cell in a Fastero notebook, on inline invented data in a demo workspace.

Notebooks can run on a cron schedule on the server with no browser open, and colleagues who only read results join as free viewers. The Free plan has no end date and needs no card: notebooks get 6 hours of compute a day on a standard machine with 1 CPU and 2 GB, and a notebook server stops after about 10 idle minutes. On Pro, a notebook can use a bigger machine, up to 8 CPUs and 32 GB at $0.80 an hour, charged by the second. Fastero has no GPU, and a package added with %pip lasts only that session. Plans: pricing.

FAQ

Is there an official pandas cheat sheet?

Yes. The pandas docs link a three-page PDF cheat sheet from their Getting started page. It covers creating, reshaping, subsetting, combining and grouping data, but has nothing on dates, pivot_table, named aggregation or the pandas 3 changes. This page adds those, with output from pandas 3.1.2.

What is the difference between loc and iloc in pandas?

loc selects by label or boolean mask, and a slice such as df.loc["a":"c"] includes the end label. iloc selects by integer position, and df.iloc[0:3] excludes position 3, like a Python list. On a Series with an integer index, pandas 3 always reads s[0] as a label, so use iloc when you mean the first row.

How do I fix SettingWithCopyWarning in pandas 3?

The warning no longer exists in pandas 3. Chained assignment such as df[mask]["col"] = x now issues a ChainedAssignmentError warning and leaves df unchanged. Write the assignment in one step with df.loc[mask, "col"] = x.

Is apply slow in pandas?

Row-wise apply(axis=1) runs Python code once per row. On 473,400 rows it took 7.9 seconds where np.where took 4.8 ms, and Series.where 7.4 ms. Use arithmetic on whole columns, where, np.where or np.select, and keep apply for logic that can't be vectorised.

What version of pandas is current, and which Python does it need?

Pandas 3.1.2, released 30 November 2026, is the current version on PyPI as of 3 December 2026. Pandas 3.x needs Python 3.11 or newer, and 3.1 needs NumPy 2.0.2 or newer. On Python 3.10 or older, pip installs pandas 2.x, whose defaults differ.

How do I reduce pandas memory usage?

Install PyArrow so text columns use the Arrow-backed str dtype, read only the columns you need with usecols, and turn repetitive text into category. On the sample, those choices took memory from 1,755 KB (pandas 2's object columns) to 210 KB. Check with df.memory_usage(deep=True).

Should I use pandas or SQL?

Use SQL to filter and aggregate where the data lives, and pandas for the reshaping, plotting and Python logic that follows. Our SQL vs pandas comparison walks through one analysis both ways, and the SQL cheat sheet and Python cheat sheet are this page's companions.

Sources

Read on 3 December 2026:


Try Fastero free: open a notebook, load the same invented sales table and run any snippet on this page in your browser. No credit card required.

Ready to try it yourself?

Connect your database, ask questions in plain English, and get live dashboards — in under 2 minutes. No credit card required.

Follow Fastero on LinkedIn for new articles and examples.