What’s New in 3.x and Migrating
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
This page was checked in October 2026 against pandas 3.1 (3.1.0, released 2026-10-22) on Python 3.13 with NumPy 2.5, and the printed output of every example was produced on those versions. It summarises what changed between pandas 2.0 and 3.1, gives a migration checklist for code written for pandas 1.x or 2.x, and ends with the places where older books and tutorials no longer match current pandas. Items from the development branch (3.2.0.dev0, unreleased) are labelled "upcoming" and may change before release.
Releases at a glance
| Version | Date | Why it matters |
|---|---|---|
2.0 |
2023-04-03 |
|
2.1 |
2023-08-30 |
|
2.2 |
2024-01-19 |
Frequency aliases |
2.3 |
2025-06-04 |
The preparation release for 3.0; 2.3.3 is the last 2.x release |
3.0 |
2026-01-21 |
Copy-on-Write only, |
3.1 |
2026-10-22 |
|
3.2 |
upcoming |
Development version 3.2.0.dev0; not released |
Both the 3.0 and the 3.1 release notes recommend upgrading to the last release of the previous line first and fixing every warning it raises, then moving up. For this reason the migration checklist below starts at 2.3.
Minimum versions
| Dependency | pandas 3.0 | pandas 3.1 |
|---|---|---|
Python |
3.11 |
3.11 |
NumPy |
1.26.0 |
2.0.2 (NumPy 1.x is no longer supported) |
PyArrow (optional) |
13.0.0 |
16.0.0 |
Matplotlib (optional) |
3.9.3 |
3.10.5 |
|
optional ( |
optional |
PyArrow is still an optional dependency. Notes from the 2.x era that said it would become required in pandas 3.0 are out of date: that change was postponed, and the str dtype falls back to a NumPy object backing when PyArrow is not installed. Install it anyway for speed and memory.
What pandas 3.0 changed
Copy-on-Write only
Every derived object behaves as a copy, chained assignment never updates the original, SettingWithCopyWarning no longer exists and arrays returned by to_numpy() can be read-only. See Copy-on-Write for the rules and the fixes.
The str dtype is the default
String columns are inferred as the dedicated str dtype instead of object. It is backed by PyArrow when installed, holds only strings or missing values, and uses NaN as the missing marker (the older opt-in "string" dtype uses pd.NA). It is described in PDEP-14.
import pandas as pd
df = pd.DataFrame({"name": ["a", "b"], "n": [1, 2]})
print(df.select_dtypes(include=["object", "string"]).columns.tolist())
print(df.select_dtypes(include="str").columns.tolist())
print(df.dtypes.astype(str).to_dict())
print(df["name"].astype(object).dtype, pd.Series(["a"], dtype="object").dtype)
ser = pd.Series(["a", None, "c"])
print(ser.map(str, na_action="ignore").tolist(), ser.map(str).tolist())
Output:
['name']
['name']
{'name': 'str', 'n': 'int64'}
object object
['a', nan, 'c'] ['a', 'nan', 'c']
The code changes the migration guide asks for are:
-
Replace
ser.dtype == objectwithpd.api.types.is_string_dtype(ser)(works on 2.x and 3.x) orser.dtype == "str"(3.x only). -
Remove hard-coded
dtype="object"for text, which keeps the old dtype, or writedtype="str". -
In
select_dtypes, passinclude=["object", "string"]to work on both versions;include=["str"]fails on 2.x. -
Test for missing values with
pd.isna, not by comparing withNoneornp.nan. -
Expect
TypeErrorwhen assigning a non-string into astrcolumn; convert withastype(object)if you really need mixed values. -
astype(str)keeps missing values missing; useser.map(str)for the old behaviour of producing the textnan. -
Series.valuesreturns an extension array forstr; useto_numpy()for a NumPy array. -
prod()on string data now raisesTypeError.
Datetime resolution and time zones
Resolution is now inferred instead of always being nanoseconds. Strings give microseconds (nanoseconds only when the text has that precision), standard-library datetime objects keep microseconds, NumPy datetime64 and timedelta64 keep their unit (limited to seconds through nanoseconds), and integer input uses the unit passed by the caller. In 3.1, numeric input with an explicit unit= gives microseconds (pd.Timestamp(1, unit="s").unit is "us"), while numbers without a unit are still nanoseconds since the epoch and give ns. The practical trap is that astype("int64") on datetimes is 1000 times smaller than code written for nanoseconds expects. Use Series.dt.as_unit("ns") where a specific resolution matters, and avoid integer casts of datetimes. The default time zone implementation is zoneinfo (and datetime.timezone for fixed offsets); pytz objects are still accepted if you pass them, but pytz is no longer installed with pandas, and ambiguous or nonexistent local times raise ValueError. pd.offsets.Day is now a calendar day that keeps the wall-clock time across a daylight-saving change, so Day(1) and Hour(24) are no longer equal.
Frequency aliases
The aliases deprecated in 2.2 were removed in 3.0, and they now raise ValueError with a suggestion.
| Meaning | Old alias (removed) | Current alias |
|---|---|---|
Month end |
|
|
Business month end |
|
|
Semi-month end |
|
|
Quarter end |
|
|
Year end |
|
|
Hour |
|
|
Minute |
|
|
Second |
|
|
Millisecond, microsecond, nanosecond |
|
|
Period and PeriodIndex frequencies keep M, Q and Y (for example freq="M" in pd.period_range), and H and A are rejected there as well. Lower-case d, b and c still work in 3.1 but emit a Pandas4Warning; use D, B and C.
import pandas as pd
sales = pd.Series(
[10, 20, 30, 40],
index=pd.date_range("2024-01-15", periods=4, freq="2W"),
)
print(sales.resample("ME").sum())
for old in ["M", "H", "T", "S"]:
try:
pd.date_range("2024-01-31", periods=2, freq=old)
except ValueError as exc:
print(old, "->", str(exc).splitlines()[0][:70])
print(pd.date_range("2024-01-31", periods=3, freq="ME").strftime("%Y-%m-%d").tolist())
print(pd.date_range("2024-01-01", periods=3, freq="h").freqstr, pd.period_range("2024-01", periods=2, freq="M").freqstr)
Output:
2024-01-31 10
2024-02-29 50
2024-03-31 40
Freq: ME, dtype: int64
M -> Invalid frequency: M. Failed to parse with error message: ValueError("
H -> Invalid frequency: H. Failed to parse with error message: ValueError('
T -> Invalid frequency: T. Failed to parse with error message: ValueError('
S -> Invalid frequency: S. Failed to parse with error message: ValueError('
['2024-01-31', '2024-02-29', '2024-03-31']
h M
Removed in 3.0 and earlier
The table lists APIs that older code still uses, when they went away and what to write now. Each name was checked by calling it on pandas 3.1.
| Removed | Gone since | Use instead |
|---|---|---|
|
2.0 |
Collect frames in a list and call |
|
2.0 |
|
|
2.0 |
|
|
1.0 |
|
|
3.0 |
|
|
3.0 |
|
|
3.0 |
Transpose, group, transpose back |
|
3.0 |
Slice the index with |
|
3.0 |
|
|
3.0 |
Catch the exception, or |
|
3.0 |
|
|
3.0 |
Replace infinities with |
|
3.0 |
The |
|
3.0 |
|
Behaviour changes in the same release include: groupby defaults to observed=True for categorical keys, DataFrame.stack uses the new implementation (the future_stack argument and the old dropna/sort arguments are being retired), assigning an incompatible value into a column raises instead of upcasting (PDEP-6), and NaN is treated as NA in nullable and Arrow-backed floating dtypes. An older change that tutorials still get wrong: since pandas 2.0, str.replace treats the pattern literally unless regex=True is passed.
import pandas as pd
rows = [{"id": i, "score": i * 1.5} for i in range(3)]
frames = [pd.DataFrame([r]) for r in rows] # collect, then concatenate once
result = pd.concat(frames, ignore_index=True)
print(result)
print(hasattr(pd.DataFrame, "append"), hasattr(pd.DataFrame, "applymap"), hasattr(pd.DataFrame, "map"))
df = pd.DataFrame({"a": [" x ", "y"]})
print(df.map(str.strip).to_dict("list"))
print(df.ffill().shape, hasattr(pd, "value_counts"), df["a"].value_counts().to_dict())
print(pd.Series(["a.b"]).str.replace(".", "-").tolist(), pd.Series(["a.b"]).str.replace(".", "-", regex=True).tolist())
Output:
id score
0 0 0.0
1 1 1.5
2 2 3.0
False False True
{'a': ['x', 'y']}
(2, 1) False {' x ': 1, 'y': 1}
['a-b'] ['---']
Source: pandas 3.0.0 release notes and pandas 2.0.0 release notes.
New in 3.0
-
pd.col()expressions, usable inassign,locand[], replace many one-offlambdacallables. -
Anti-joins:
how="left_anti"andhow="right_anti"inmergeandjoin. -
read_iceberg()andDataFrame.to_iceberg()for Apache Iceberg tables,DataFrame.from_arrow()andSeries.from_arrow()through the Arrow PyCapsule interface. -
A
skipnaargument for groupby reductions,Rolling.first,Rolling.last,Rolling.nunique,ilocwith boolean masks,to_sql(if_exists="delete_rows")and half-year offsets. -
The three-stage deprecation policy of PDEP-17 (below).
What pandas 3.1 changed
| Change | Details |
|---|---|
|
Select columns by label or |
|
Filter rows with a boolean mask, callable or |
Parallel |
The C engine reads local, uncompressed files of at least 5 MB in parallel by default; |
Resolution for numeric input |
|
Read-only index arrays |
|
|
Dtype instances match exactly; |
|
Numeric and boolean columns get numeric or boolean categories; use |
|
|
HDF5 |
Files written with |
Build |
C++20 is required to build from source |
import pandas as pd
df = pd.DataFrame({"name": ["a", "b"], "n": [1, 2]})
print(df.assign(m=pd.col("n") * 10).select("name", total=pd.col("n") + pd.col("n")))
Output:
name total 0 a 2 1 b 4
Source: pandas 3.1.0 release notes.
inplace is deprecated for methods that are not truly in place
Since 3.1 the inplace= keyword emits a Pandas4Warning on drop, rename, rename_axis, reset_index, set_index, dropna, drop_duplicates, sort_values, sort_index, eval and query (PDEP-8). These methods always built a new object internally, so the keyword saved nothing. Reassign instead: df = df.reset_index(). fillna and replace keep the keyword for now, although inplace=True on a column selection no longer reaches the parent frame (see Copy-on-Write).
Other 3.1 deprecations worth knowing
| Deprecated in 3.1 | Replacement |
|---|---|
|
|
|
Delete; |
|
Always on in pandas 4.0 |
|
|
|
|
|
|
|
|
|
|
|
Cast first; the change will become an error |
The deprecation policy (PDEP-17)
Since 3.0, a deprecation moves through three stages: a PandasDeprecationWarning (a DeprecationWarning subclass, quiet by default outside tests), a PandasFutureWarning (a FutureWarning subclass, shown to users) in the last minor release before removal, and removal in the next major version. The base class is pandas.errors.PandasChangeWarning, and each warning names the version that will remove the feature: Pandas4Warning means pandas 4.0. Because Pandas4Warning is a DeprecationWarning, test suites should turn it into an error so that deprecations surface while they are still cheap to fix.
import warnings
import pandas as pd
print([c.__name__ for c in pd.errors.Pandas4Warning.__mro__[:4]])
df = pd.DataFrame({"a": [3, 1, 2]})
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
work = df.copy()
work.sort_values("a", inplace=True) # deprecated in 3.1
print([type(w.message).__name__ for w in caught])
df = df.sort_values("a") # reassign instead
print(df["a"].tolist())
warnings.filterwarnings("error", category=pd.errors.Pandas4Warning)
try:
pd.DataFrame({"a": [1]}).reset_index(inplace=True)
except pd.errors.Pandas4Warning as exc:
print("escalated:", type(exc).__name__)
Output:
['Pandas4Warning', 'PandasDeprecationWarning', 'PandasChangeWarning', 'DeprecationWarning'] ['Pandas4Warning'] [1, 2, 3] escalated: Pandas4Warning
Source: pandas 3.0.0 release notes (deprecation policy) and PDEP-17.
Migration checklist
-
Upgrade to Python 3.11 or newer and, for pandas 3.1, NumPy 2.0.2 or newer (see Migrating to NumPy 2.x).
-
Move to pandas 2.3 (2.3.3 is the last 2.x release) and run the tests with deprecation warnings turned into errors. Fix every warning.
-
In 2.3, try
pd.options.future.infer_string = Trueandpd.options.mode.copy_on_write = "warn", and repair the code they flag. The Copy-on-Write warnings are intentionally broad, so you do not need to clear every one. -
Replace removed APIs using the table above, including frequency aliases (
ME,QE,YE,h,min) andDataFrame.mapforapplymap. -
Replace chained assignment with a single
loccall, removeSettingWithCopyWarninghandling, and stop writing into arrays fromto_numpy(). -
Replace
objectdtype checks andselect_dtypes(include=object)with the string-aware forms. -
Review datetime-to-integer casts and any code that assumes nanosecond resolution.
-
Move to 3.0, then 3.1, fixing
Pandas4Warningmessages as they appear; reassign instead of usinginplace=True. -
Pin the tested range in
pyproject.toml(for examplepandas>=3.1,<4), and read the release notes of every minor release.
Upcoming (unreleased)
The following items come from the 3.2.0 development notes and may still change: read_csv(sep=None) separator sniffing with the C engine, Categorical.to_dense(), DatetimeIndex.set_freq(), Series.groupby(as_index=False), a deprecation of pandas.to_pickle in favour of the object methods, an error for suffix collisions in merge, and a ValueError from DataFrame.query when the expression is not boolean. Pandas 4.0 will remove the deprecated options and every feature marked with a Pandas4Warning. Treat all of this as planned, not available.
Where older books and tutorials are outdated
Most of what is still taught about pandas was written for versions before 2.0. When a book or tutorial disagrees with the pages in this section, the official documentation wins. The tables name the editions and their dates only to help you translate the examples you may meet; they do not reproduce any text.
Books
| Book (publication) | Targets | What to translate |
|---|---|---|
McKinney, Python for Data Analysis, 2nd edition (O’Reilly, 2017) |
Python 3.6, pandas 0.20 and 0.21, NumPy 1.13 |
Removed accessors and functions ( |
Igual and Seguí, Introduction to Data Science (Springer, 2017) |
Python 2.7, pandas about 0.18 |
Python 2 |
Géron, Hands-On Machine Learning with Scikit-Learn and TensorFlow (O’Reilly, 2017) |
scikit-learn about 0.18, TensorFlow 1 |
Mostly scikit-learn and TensorFlow API changes, which the scikit-learn pages cover; check any pandas snippet against the removed-API table |
Géron, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd edition (O’Reilly, 2019; early release) |
scikit-learn 0.20, TensorFlow 2 |
|
Géron, Hands-On Machine Learning with Scikit-Learn and PyTorch (O’Reilly, 2025) |
scikit-learn 1.5 or newer, Python 3.12 and 3.13 |
The most current of the set, but it predates pandas 3: |
The other books in the reading list (Skiena, Hunt, Marsland, Moroney, LazyProgrammer and Skansi) are not pandas books and contain little or no pandas code; their gaps lie elsewhere and are covered in the other parts of this section.
Tutorials and answers written before 2024
| Typical advice | Current situation |
|---|---|
"Ignore |
The warning is gone; chained assignment does nothing; defensive copies are unnecessary. See Copy-on-Write |
Build a DataFrame by calling |
|
|
Removed in 3.0; use |
|
All removed; see the table of removed APIs |
|
Text is |
"PyArrow will be required in pandas 3.0" |
Postponed; PyArrow stays optional |
|
It never did for most methods and is deprecated in 3.1 |
|
The unit now depends on the data; use |
Regular-expression behaviour of |
A literal match by default since 2.0; pass |
Related pages
-
Pandas for the overview and bibliography.
-
Installation and Versions for installing and pinning pandas.
References
-
pandas 3.2.0 development notes (upcoming)