pandas 3.0 arrived on 21 January 2026 and pandas 3.1 followed on 22 October 2026. Together they are the biggest change to the library in more than ten years. Your old scripts will mostly still run, but some lines now quietly do nothing, some raise errors, and a few return numbers that are 1000 times smaller than before. The good news: the new rules are simpler, and once you know them your code becomes shorter and faster. In this guide we upgrade step by step and run every example on pandas 3.1.1. You will see the new str dtype, Copy-on-Write and the end of SettingWithCopyWarning, the pd.col() expression syntax, the new DataFrame.select() and filter(cond=...) methods, the datetime and offset changes, and the parallel CSV reader. Every output block below is the real output of the script above it.
What changed in pandas 3 (quick summary)
- Strings get their own dtype. Text columns are inferred as
str(backed by PyArrow when it is installed) instead ofobject. - Copy-on-Write is always on. Every subset or method result behaves like a copy. Chained assignment never works, and
SettingWithCopyWarningis gone. pd.col()expressions replace manylambda df: df["x"]callables (3.0), and 3.1 addsDataFrame.select()and booleanfilter(cond=...).- Datetimes default to microseconds instead of nanoseconds, time zones use the standard library
zoneinfo, and old offset aliases such as"M","Q"and"Y"are removed. read_csvis faster in 3.1 and reads large local files in parallel by default.- Requirements: Python 3.11 or newer and NumPy 1.26 or newer;
pytzis no longer installed automatically.
Setup
The pandas team recommends upgrading in two hops: first move to pandas 2.3 and fix every FutureWarning and DeprecationWarning, then jump to 3.x. Install PyArrow too, because it powers the fast string dtype and the Parquet reader (see our PyArrow Tables and Parquet tutorial).
uv venv -p 3.15 && source .venv/bin/activate # any Python 3.11+
uv pip install "pandas>=3.1" pyarrow
python -W always step1_strings.py # show every warning while migrating
Step 1: The new str dtype
Before pandas 3, a column of names had dtype object, which can hold any Python object. Now pandas infers a dedicated string dtype, shown simply as str. Missing values are still NaN, so isna() works as before.
import pandas as pd
print("pandas", pd.__version__)
names = pd.Series(["Ana", "Bilal", None, "Chen"])
print(names.dtype) # str, not object
print(names.isna().tolist()) # missing value is NaN
old = names.astype(object)
big = pd.Series(["product-" + str(i % 500) for i in range(200_000)])
print("str MB: ", round(big.memory_usage(deep=True) / 1e6, 1))
print("object MB:", round(big.astype(object).memory_usage(deep=True) / 1e6, 1))
# Old check breaks, new check works
print("dtype == object:", names.dtype == object)
print("is_string_dtype:", pd.api.types.is_string_dtype(names))
try:
names[0] = 42 # str columns only hold strings
except TypeError as e:
print("TypeError:", e)
pandas 3.1.1
str
[False, False, True, False]
str MB: 3.8
object MB: 12.0
dtype == object: False
is_string_dtype: True
TypeError: Invalid value '42' for dtype 'str'. Value should be a string or missing value, got 'int' instead.
Three things to notice. First, the same 200,000 product names use 3.8 MB as str but 12.0 MB as object, more than three times less memory. Second, any check like df[col].dtype == object now returns False for text columns, so such checks silently skip them. select_dtypes(include="object") still returns text columns for backward compatibility, but it emits a Pandas4Warning and will stop doing so in a future version. Replace these checks with pd.api.types.is_string_dtype() or select_dtypes(include="str"). Third, a str column only accepts strings or missing values; writing the integer 42 raises a clear TypeError. If you really need mixed values, convert the column with astype(object) on purpose.
Step 2: Copy-on-Write and the end of SettingWithCopyWarning
For years pandas users fought SettingWithCopyWarning, because whether a subset was a view or a copy depended on the exact operation. pandas 3 makes one simple rule: any indexing result or method result behaves as a copy. If you want to change a DataFrame, change that DataFrame directly, in one step.
import warnings
import numpy as np
import pandas as pd
df = pd.DataFrame({"city": ["Lahore", "Paris", "Austin"], "temp": [31, 18, 25]})
# 1) Chained assignment never updates df in pandas 3
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
df[df["temp"] > 20]["temp"] = 0
print(type(caught[0].message).__name__)
print(df["temp"].tolist())
# 2) The correct way: one .loc call on the object itself
df.loc[df["temp"] > 20, "temp"] = 0
print(df["temp"].tolist())
# 3) A subset always behaves like a copy (no SettingWithCopyWarning)
hot = df[df["city"] != "Paris"]
hot["temp"] = 99
print(df["temp"].tolist(), hot["temp"].tolist())
# 4) Copies are lazy: memory is shared until someone writes
col = df["temp"]
print("shares memory:", np.shares_memory(col.to_numpy(), df["temp"].to_numpy()))
col.iloc[0] = -5
print("after write: ", np.shares_memory(col.to_numpy(), df["temp"].to_numpy()))
print(df["temp"].tolist(), col.tolist())
ChainedAssignmentError
[31, 18, 25]
[0, 18, 0]
[0, 18, 0] [99, 99]
shares memory: True
after write: False
[0, 18, 0] [-5, 18, 0]
The first line is classic chained assignment: df[mask]["temp"] = 0. In pandas 3 it never updates df; the temperatures stay [31, 18, 25] and pandas emits a ChainedAssignmentError warning that points you to .loc. The single-step df.loc[mask, "temp"] = 0 works. Changing the subset hot no longer warns and never touches df, so you can delete all those defensive .copy() calls you added to silence the old warning. Finally, Copy-on-Write is lazy: col shares memory with df until you write to it, and only then does pandas copy the data. That is why pandas 3 often uses less memory than pandas 2, not more.
The same rule breaks a popular in-place pattern: df["temp"].fillna(0, inplace=True) and df["temp"].replace(..., inplace=True) no longer change df. pandas warns with a ChainedAssignmentError here too. Write df["temp"] = df["temp"].fillna(0) or df.fillna({"temp": 0}, inplace=True) instead.
Step 3: pd.col expressions, select() and filter(cond=...)
Method chains used to need small lambdas such as assign(revenue=lambda d: d["price"] * d["qty"]). pandas 3.0 added pd.col("name"), an expression that refers to a column of whatever DataFrame it is used on. It supports arithmetic, comparisons and Series methods such as .str.upper(). pandas 3.1 adds DataFrame.select(), which picks and computes columns in one call, and lets filter() keep rows with a boolean condition.
import pandas as pd
sales = pd.DataFrame({
"product": ["laptop", "mouse", "monitor", "desk"],
"price": [1200, 25, 300, 450],
"qty": [3, 40, 5, 2],
})
# pd.col replaces lambda df: df["..."] (pandas 3.0)
out = sales.assign(revenue=pd.col("price") * pd.col("qty"))
print(out)
# Filter rows with an expression inside .loc
print(out.loc[pd.col("revenue") > 1000, "product"].tolist())
# DataFrame.select and filter(cond=...) (pandas 3.1)
report = (
sales
.filter(pd.col("qty") >= 3)
.select("product", revenue=pd.col("price") * pd.col("qty"),
name=pd.col("product").str.upper())
)
print(report)
product price qty revenue
0 laptop 1200 3 3600
1 mouse 25 40 1000
2 monitor 300 5 1500
3 desk 450 2 900
['laptop', 'monitor']
product revenue name
0 laptop 3600 LAPTOP
1 mouse 1000 MOUSE
2 monitor 1500 MONITOR
The assign call computes revenue without a lambda, .loc[pd.col("revenue") > 1000, "product"] keeps only the laptop and monitor rows, and the final chain filters on qty >= 3 and builds a three-column report with new names. If this looks familiar, it is because Polars works the same way with pl.col(); our Polars vs pandas benchmarks compare the two libraries in more depth. Note that the old meaning of filter(), selecting labels with items, like or regex, still works but is planned for deprecation.
Step 4: Datetimes, time zones and offset aliases
Parsing strings now gives datetime64[us] (microseconds) instead of datetime64[ns]. Values look identical, but converting to integers gives numbers 1000 times smaller, which can break epoch timestamps you send to databases or APIs.
import pandas as pd
ts = pd.to_datetime(pd.Series(["2026-11-28 08:00", "2026-11-29 09:30"]))
print(ts.dtype) # microseconds now
print(ts.astype("int64").iloc[0]) # 1000x smaller than ns
print(ts.dt.as_unit("ns").astype("int64").iloc[0]) # unit-safe epoch ns
local = ts.dt.tz_localize("Asia/Karachi")
print(type(local.dt.tz).__name__, local.dt.tz) # zoneinfo, not pytz
daily = pd.Series(range(90), index=pd.date_range("2026-01-01", periods=90, freq="D"))
print(daily.resample("ME").sum().tolist())
try:
daily.resample("M").sum()
except ValueError as e:
print("ValueError:", e)
datetime64[us]
1795852800000000
1795852800000000000
ZoneInfo Asia/Karachi
[465, 1246, 2294]
ValueError: Invalid frequency: M. Failed to parse with error message: ValueError("'M' is no longer supported for offsets. Please use 'ME' instead.")
The epoch value is 1,795,852,800,000,000 microseconds; call .dt.as_unit("ns") first when another system expects nanoseconds. Time zones created from strings are now zoneinfo.ZoneInfo objects from the standard library, not pytz objects; if your code calls pytz-only methods such as .localize(), install pytz yourself or switch to zoneinfo (see our guide to time zones in pandas). Monthly resampling with "ME" gives the three monthly totals, while the old alias "M" now raises a ValueError. Rename "M", "Q" and "Y" to "ME", "QE" and "YE" (and "BM" to "BME") everywhere.
Step 5: Faster read_csv with parallel reads (pandas 3.1)
pandas 3.1 rewrote large parts of the default C CSV reader. A local, uncompressed file of at least 5 MB is now split and read on several threads automatically. The new option mode.max_threads controls this; it defaults to the number of CPUs available, capped at 6, and setting it to 1 forces a serial read. We create a 61 MB file with 1.5 million orders and compare.
import os
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
n = 1_500_000
pd.DataFrame({
"order_id": np.arange(n),
"city": rng.choice(["Lahore", "Paris", "Austin", "Tokyo"], n),
"amount": rng.uniform(5, 500, n).round(2),
"ts": pd.date_range("2026-01-01", periods=n, freq="s").astype(str),
}).to_csv("orders.csv", index=False)
print(f"orders.csv: {os.path.getsize('orders.csv') / 1e6:.0f} MB, {os.cpu_count()} CPUs")
def best_of_3(threads):
times = []
with pd.option_context("mode.max_threads", threads):
for _ in range(3):
start = time.perf_counter()
df = pd.read_csv("orders.csv")
times.append(time.perf_counter() - start)
return df, min(times)
serial, t1 = best_of_3(1) # force a single-threaded read
parallel, tn = best_of_3(None) # default: CPUs available, capped at 6
print(f"serial: {t1:.3f}s")
print(f"parallel: {tn:.3f}s ({t1 / tn:.1f}x faster)")
print("identical:", serial.equals(parallel))
print(parallel.dtypes.to_dict())
os.remove("orders.csv")
orders.csv: 61 MB, 8 CPUs
serial: 0.130s
parallel: 0.040s (3.3x faster)
identical: True
{'order_id': dtype('int64'), 'city': <StringDtype(na_value=nan)>, 'amount': dtype('float64'), 'ts': <StringDtype(na_value=nan)>}
The serial read took 0.130 seconds and the default parallel read 0.040 seconds, 3.3 times faster, with an identical result. You get this speed-up with no code change. Set mode.max_threads to 1 when pandas runs inside something that already uses all cores, such as a process pool (our multiprocessing tutorial explains why oversubscribing cores hurts). Also notice the dtypes: city and ts are the new string dtype, so convert timestamps with pd.to_datetime() after reading.
pandas 3 migration checklist
- Upgrade to pandas 2.3 first and run your tests with
python -W error::FutureWarning. - Search for chained assignment (
df[...][...] =) and column-levelinplace=True; rewrite them with one.loccall or plain assignment. - Delete defensive
.copy()calls that only existed to silenceSettingWithCopyWarning. - Replace
dtype == objectandinclude="object"checks for text withis_string_dtypeorinclude="str". - Before
astype("int64")on datetimes, call.dt.as_unit("ns")or the unit you need. - Rename offset aliases
M,Q,Y,BMtoME,QE,YE,BME. - Add
pytzto your requirements only if you still use pytz objects directly. - Pin
pandas>=3.1,<4and run your test suite once more.
Common errors after upgrading and their fixes
- ChainedAssignmentError warning and the DataFrame does not change: you assigned through two indexing steps. Use
df.loc[rows, "col"] = value. - TypeError: Invalid value ... for dtype 'str': you wrote a number or object into a text column. Convert the value to a string, or make the column
objecton purpose. - ValueError: Invalid frequency: M: use
"ME"(month end); likewise"QE"and"YE". - Epoch numbers are 1000 times too small: the column is microseconds; use
as_unit("ns")before converting to integers. - ModuleNotFoundError: No module named 'pytz': pytz is now optional;
pip install "pandas[timezone]"or move tozoneinfo.
Conclusion
pandas 3 trades a few breaking changes for a much clearer model: strings have a real dtype that uses about three times less memory in our test, every subset behaves like a copy, so .loc in one step is the only way to modify data, and pd.col() with select() makes method chains readable without lambdas. pandas 3.1 adds a CSV reader that was 3.3 times faster on our 8-core machine with zero code changes. Work through the checklist, run your tests with warnings turned on, and most projects can upgrade in an afternoon.
FAQ
Is SettingWithCopyWarning removed in pandas 3? Yes. Because every subset now behaves like a copy, the warning is no longer needed. Chained assignment instead triggers a ChainedAssignmentError warning and never changes the original.
Do I need PyArrow for pandas 3? No, but it is recommended. Without PyArrow the str dtype falls back to NumPy object storage and loses most of its speed and memory benefits.
Can I turn Copy-on-Write off? No. In pandas 3 it is the only behaviour; the old mode.copy_on_write option no longer switches it off.
Which Python version does pandas 3 need? Python 3.11 or newer. We tested on Python 3.15.2.
Should I switch to Polars instead? For new, very large pipelines Polars is worth a look, but pandas 3 closes much of the gap with Arrow strings, lazy copies and parallel CSV reading, and it keeps the huge pandas ecosystem.
Tested versions: Python 3.15.2 (CPython), pandas 3.1.1, NumPy 2.5.5 and PyArrow 26.0.1 on Linux x86_64 with 8 CPU cores.