Migrating to NumPy 2.x
|
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 written in October 2026. The current release was NumPy 2.5.4 (2026-10-10), which supports Python 3.12 to 3.15. Examples target Python 3.13 or 3.14 and were run on Python 3.13, with NumPy 2.5.4 unless an example says otherwise. The Ruff output comes from Ruff 0.17.3.
NumPy 2.0 (2024-06-16) was the first major release in about eighteen years and the first to break the Python and the C interfaces on purpose. Most of the breakage was a clean-up of duplicate names and legacy behaviour; the rest was a change to how scalars are promoted, which NEP 50 had announced. The releases after 2.0 kept removing things that had been deprecated, so a program that ran without warnings on 2.0 can still break on 2.4 or 2.5. This page follows the order you will meet the changes in.
For the new features of each release, see What’s New in NumPy 2.1 to 2.5. For installing a specific version, see Installation and Versions.
A migration plan
-
Work on NumPy 1.26 first and fix every deprecation warning. Removals are announced a release ahead.
-
Run Ruff’s
NPY201rule and apply the safe fixes. -
Upgrade, run your tests with warnings turned into errors, and fix what remains.
-
Rebuild any compiled dependency of your own. Wheels built against NumPy 1.x do not work with NumPy 2, and your dependencies must have NumPy 2 wheels.
-
Decide the supported range (for example
numpy>=1.26,<3ornumpy>=2.0) and test the oldest and newest versions in your continuous integration.
Source: NumPy 2.0 migration guide
Step 1: automated fixes with Ruff NPY201
The migration guide recommends the NPY201 rule of Ruff (version 0.4.8 or later). It reports every name that NumPy 2.0 removed and rewrites those that have an exact replacement.
# pyproject.toml
[tool.ruff.lint]
select = ["NPY201"]
ruff check path/to/code/ --select NPY201 # report
ruff check path/to/code/ --select NPY201 --fix # apply the safe fixes
On a file that uses six removed names, Ruff 0.17.3 reported:
old.py:3:5: NPY201 [*] `np.float_` will be removed in NumPy 2.0. Use `numpy.float64` instead.
old.py:4:5: NPY201 [*] `np.NaN` will be removed in NumPy 2.0. Use `numpy.nan` instead.
old.py:5:5: NPY201 [*] `np.product` will be removed in NumPy 2.0. Use `numpy.prod` instead.
old.py:6:5: NPY201 `np.trapz` will be removed in NumPy 2.0. Use `numpy.trapezoid` on NumPy 2.0, or ignore this warning on earlier versions.
old.py:7:5: NPY201 `np.in1d` will be removed in NumPy 2.0. Use `np.isin` instead. ...
old.py:8:5: NPY201 [*] `np.row_stack` will be removed in NumPy 2.0. Use `numpy.vstack` instead.
Found 6 errors.
[*] 4 fixable with `--fix` (1 unsafe fix available with `--fix --unsafe-fixes`).
The two names without a safe fix are the ones whose replacement does not exist on NumPy 1.x or behaves differently: np.trapezoid appeared in NumPy 2.0, and np.isin keeps the input shape where np.in1d flattened it. If you support both major versions you must decide those by hand. Ruff changes only what it can recognise, so a lint pass is a starting point, not proof that the code is migrated.
Step 2: removed names and their replacements
NumPy 2.0 trimmed the main namespace. The table lists the most common removals from the migration guide with the replacement that works on NumPy 2, and (where there is one) on 1.x too.
| Removed in 2.0 | Use instead |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
the |
|
|
|
|
|
|
|
|
|
|
|
an IDE, your own printing function, |
|
|
|
private: it became |
Other namespace changes in 2.0:
-
np.libnow contains only a short list (for examplearray_utils,format,mixins,npyio,scimath,stride_tricks,NumpyVersion). Functions that used to be reachable asnp.lib.xxxlive in the main namespace. -
numpy.stringsis a new namespace of string ufuncs. Prefer it tonumpy.char; in 2.5numpy.char.chararrayandnumpy.char.arrayare deprecated. -
numpy.array_apiwas removed; the main namespace follows the array API standard instead (see The Array API Standard). -
np.exceptionsholdsAxisError,ComplexWarning,VisibleDeprecationWarningand the other exception classes.
Names that were still available in 2.0 as deprecated and were then removed in later releases:
| Removed in | Name | Use instead |
|---|---|---|
2.3 (2025-06-07) |
|
|
2.4 (2025-12-20) |
|
|
2.4 |
|
|
2.4 |
|
|
2.4 |
|
|
2.4 |
|
|
2.5 (2026-06-21) |
|
|
2.5 |
|
Meson, |
2.5 |
the |
|
2.5 |
|
|
The effect of a removed name is an AttributeError, which is easy to spot:
import numpy as np
for name in ["float_", "NaN", "Inf", "trapz", "in1d", "row_stack", "product",
"string_", "asfarray", "mat", "alltrue", "round_", "cast",
"find_common_type", "infty"]:
print(name, hasattr(np, name))
Every line printed False on NumPy 2.5.4.
print(np.trapezoid([1, 2, 3]), np.isin([1, 2], [2]), np.vstack([[1], [2]]).shape)
try:
np.quantile([1, 2, 3, 4], 0.3, interpolation="linear")
except TypeError as e:
print("TypeError:", e)
print(np.quantile([1, 2, 3, 4], 0.3, method="linear"))
Output:
4.0 [False True] (2, 1)
TypeError: quantile() got an unexpected keyword argument 'interpolation'
1.9
Source: NumPy 2.0 migration guide, 2.3.0, 2.4.0 and 2.5.0 release notes
Step 3: behaviour changes that do not raise errors
The silent changes are the dangerous ones. Test them with real data.
NEP 50 promotion: Python scalars are weak
Before NumPy 2, the result type of an operation with a scalar depended on the scalar’s value. In NumPy 2 a Python int, float or complex is "weak": it adopts the dtype of the NumPy operand. NumPy scalars are "strong" and keep their own dtype.
import numpy as np
print(repr(np.float32(3) + 3.0), (np.float32(3) + 3.0).dtype)
print((np.uint8(1) + 2).dtype, (np.array([3], dtype=np.float32) + np.float64(3)).dtype)
try:
np.int8(1) + 1000
except OverflowError as e:
print("OverflowError:", e)
Output:
np.float32(6.0) float32
uint8 float64
OverflowError: Python integer 1000 out of bounds for int8
The first line used to give a float64. The last line used to silently produce a larger integer type. To find affected code on a 1.x or 2.0 interpreter, the guide mentions np._set_promotion_state("weak_and_warn"), which warns where the result changes; expect many warnings that do not matter. Fixes are explicit casts or converting to Python scalars with int(), float() or .item(). The 2.2 release removed the NEP 50 escape hatch, so legacy promotion can no longer be switched back on. The full rules are in Type Promotion (NEP 50).
The default integer and the scalar repr
On Windows 64-bit the default integer is now 64-bit (it was 32-bit because it followed the C long). Code that passes such arrays to a library that expects long must cast explicitly with arr.astype("long", copy=False). The numpy.random API is not affected.
NEP 51 changed the representation of scalars, so doctests and notebooks that compare printed output change:
print(np.arange(3).dtype, repr(np.float64(3.0)), repr(np.array([1.5])[0]))
with np.printoptions(legacy="1.25"):
print(repr(np.float64(3.0)))
Output:
int64 np.float64(3.0) np.float64(1.5)
3.0
np.printoptions(legacy="1.25") restores the old text, which is the fastest way to keep an old doctest suite passing while you update it. str() is unchanged; only repr() includes the type.
Source: NumPy 2.0 migration guide
The copy keyword
Before NumPy 2, np.array(x, copy=False) meant "copy only if needed". In NumPy 2, copy=False means "never copy" and raises ValueError if a copy is unavoidable. A third value, copy=None, means "copy only if needed". Replace np.array(x, copy=False) with np.asarray(x).
try:
np.array([1, 2], copy=False, dtype=np.float64)
except ValueError as e:
print("ValueError:", str(e).splitlines()[0])
print(np.asarray([1, 2], dtype=np.float64), np.array([1, 2], copy=None, dtype=np.float64))
Output:
ValueError: Unable to avoid copy while creating an array as requested.
[1. 2.] [1. 2.]
If you write a class with an __array__ method, it must accept dtype=None, copy=None and honour them. copy=True always returns a new array, copy=None copies only when required (for example by dtype), and copy=False raises ValueError if a copy would be needed.
Linear algebra and numerical results
-
numpy.linalg.eigandeigvalsalways return complex arrays from NumPy 2.5; before they returned a real array when all eigenvalues were real. Useeighoreigvalshfor symmetric or Hermitian matrices, which return real values. To keep the old behaviour:w = eigvals(a), thenif np.any(w.imag == 0): w = w.real, exactly as the release notes show. -
vecdot,matrix_transpose,.mT,matrix_norm,vector_normandsvdvalsare new in 2.0;matvecandvecmatarrived in 2.2.lstsqchanged the default ofrcondandsolvechanged its broadcasting rules in 2.0. In 2.5.4,svdandlstsqraise for inputs with infinities instead of returning garbage. -
numpy.covwith a single-row matrix androwvar=Falsereturns an array, not a scalar (2.2). Norms of empty arrays return zero (2.3). -
np.histogramautomatic binning changed in 2.1 and 2.3. Do not compare stored bin edges across versions.
w = np.linalg.eigvals(np.array([[2.0, 0], [0, 3.0]]))
print(w, w.dtype)
print(np.linalg.eigvalsh(np.array([[2.0, 0], [0, 3.0]])).dtype)
Output:
[2.+0.j 3.+0.j] complex128
float64
Source: NumPy 2.5.0 release notes and numpy.linalg.eigvals
Sorting, rounding, truth values and shapes
print(np.sort(np.array([3, 1, 2]), descending=True)) # new in 2.5
print(np.sort(np.array([3, 1, 2, 7]), stable=True)) # new in 2.0
a = np.arange(6.0)
print(np.round(a) is a) # 2.4: always a copy
try:
bool(np.array([])) # 2.2: error
except ValueError as e:
print("ValueError:", e)
b = np.arange(6)
b.shape = (2, 3) # DeprecationWarning in 2.5; use b = b.reshape(2, 3)
Output:
[3 2 1]
[1 2 3 7]
False
ValueError: The truth value of an empty array is ambiguous. Use `array.size > 0` to check that an array is not empty.
Source: NumPy 2.5.0 release notes, 2.4.0, 2.2.0 and numpy.sort
The last assignment emits a DeprecationWarning on 2.5.4 ("Setting the shape on a NumPy array has been deprecated"). Assignment to arr.dtype and arr.strides is deprecated in the same way; use reshape, view and np.lib.stride_tricks. np.fix is deprecated in 2.5 (use np.trunc).
Other silent changes: np.unique on strings and complex numbers may return unsorted results in 2.3 and 2.4 (pass sorted=True where order matters), numpy.where with an out-of-range Python integer raises instead of truncating (2.5), meshgrid always returns a tuple (2.5), and Generator.binomial and Generator.multinomial produce a different stream for the same seed in 2.5 (legacy RandomState is unchanged).
where= without out=
From 2.4 a ufunc called with where= and no out= warns, because the positions where the condition is false hold uninitialised memory. Pass out= (or out=None to silence the warning).
import warnings
with warnings.catch_warnings(record=True) as ws:
warnings.simplefilter("always")
np.add(np.arange(3), 1, where=np.array([True, False, True]))
print([w.category.__name__ for w in ws])
print(np.add(np.arange(3), 1, where=np.array([True, False, True]),
out=np.zeros(3, dtype=int)))
Output:
['UserWarning']
[1 0 3]
numpy.matrix and np.mat
numpy.matrix is no longer recommended, even for linear algebra: use 2-D ndarray objects and the @ operator. np.mat is gone; np.asmatrix still exists for old code. Tutorials that build "matrices" with np.mat should be rewritten with np.array (see Linear Algebra).
Step 4: find the warnings before they become errors
The surest way to see deprecations is to make them fail in the test suite.
python -W error::DeprecationWarning -m pytest
or, in pyproject.toml:
[tool.pytest.ini_options]
filterwarnings = [
"error::DeprecationWarning:numpy",
"error::numpy.exceptions.VisibleDeprecationWarning",
]
Check the pytest documentation for the exact filter syntax your version accepts. np.testing.assert_warns and np.testing.suppress_warnings are deprecated in 2.4; use pytest.warns or warnings.catch_warnings instead.
Supporting NumPy 1.x and 2.x in one code base
-
Prefer code that works on both. Most of the replacements above exist on 1.26 (
np.float64,np.nan,np.prod,np.round,np.asarray). -
For the few that differ, branch with
numpy.lib.NumpyVersion:
import numpy as np
if np.lib.NumpyVersion(np.__version__) >= "2.0.0":
from numpy.exceptions import AxisError
else:
from numpy import AxisError
trapezoid = np.trapezoid if hasattr(np, "trapezoid") else np.trapz
-
Pickles written by NumPy 2.0 load on 1.26, and the reverse works; NumPy 1.25 and earlier cannot read 2.0 pickles.
-
Compiled extensions: build against NumPy 2.x to produce wheels that run on both major versions (see C-API, Cython and F2PY).
-
Set both a lower and an upper bound on NumPy in applications you ship, and relax the upper bound only after testing.
Source: NumPy 2.0 migration guide
Where older books and tutorials are outdated
Printed books and tutorials freeze the NumPy API of the year they were written. The table lists patterns you will meet, with the date of the release that changed them and what to write today. It describes the patterns, not any text, and it applies equally to blog posts and course notes written in the same period. When a book and the official documentation disagree, follow the official documentation.
| Pattern in older material | Changed | What to write on NumPy 2.5 |
|---|---|---|
|
Called "discouraged" in the random documentation; the legacy |
|
|
Legacy generator, kept only for stream compatibility |
|
|
Removed in 2.0 (2024-06-16) |
|
|
Removed in 2.0 |
|
|
Removed in 2.4 (2025-12-20) |
|
|
Removed in 2.5 (2026-06-21) |
|
|
|
|
Results printed as |
Scalar repr includes the type (2.0, NEP 51) |
Expect |
|
NEP 50 (2.0): Python scalars are weak |
Read Type Promotion (NEP 50); cast explicitly |
Default integer |
|
Pass |
|
|
Use public names |
|
"No longer recommended" (and |
2-D |
|
Legacy API |
|
|
|
|
Eigenvalues of real matrices returned as a real array |
|
|
|
Deprecated in 2.4 and 2.5 |
|
|
Removed in 2.5 |
|
The books and courses most often used alongside this section fall into three groups by the NumPy they were written for. The NumPy-related points are listed, with the year of publication, so that you can tell which parts still hold.
| Title (edition, year) | Written for | NumPy-related content that is outdated today |
|---|---|---|
McKinney, Python for Data Analysis (2nd edition, 2017) |
Python 3.6, NumPy 1.13 |
|
Géron, Hands-On Machine Learning with Scikit-Learn and TensorFlow (2017) |
scikit-learn 0.18, TensorFlow 1 |
|
Géron, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (2nd edition, 2019; early release) |
scikit-learn 0.20, TensorFlow 2 |
|
Géron, Hands-On Machine Learning with Scikit-Learn and PyTorch (2025) |
scikit-learn 1.5 or later, Python 3.12 and 3.13 |
The most recent of the group: it already uses |
Marsland, Machine Learning: An Algorithmic Perspective (2nd edition, 2015) |
Python 2, NumPy 1.x, |
|
LazyProgrammer, Deep Learning in Python (2016) |
Python 2, Theano, TensorFlow 1 |
|
Skansi, Introduction to Deep Learning (2018) |
Python 3.5 and 3.6, Keras 2 |
An unseeded |
Moroney, AI and ML for Coders in PyTorch (2025) |
PyTorch 2 |
|
Igual and Seguí, Introduction to Data Science (1st edition, 2017) |
Python 2.7, pandas 0.18 |
Python 2 |
Hunt, Advanced Guide to Python 3 Programming (2019) |
Python 3.7, Matplotlib 3 |
|
Three rules of thumb follow. Books written for Python 2 or for NumPy 1.1x need every listing ported, although their array ideas hold. Books from 2022 to 2025 use the 1.x spelling of the names in the tables above but are otherwise close to current practice. Everything published before June 2024 predates the NumPy 2.0 removals, and everything before June 2026 predates the 2.5 ones.
The pandas and scikit-learn parts of this section keep their own lists for the library-specific differences.
Quick reference: what changed when
| Release (date) | Migration-relevant change |
|---|---|
2.0 (2024-06-16) |
Main namespace trimmed, NEP 50 and NEP 51, default integer, |
2.1 (2024-08-18) |
|
2.2 (2024-12-08) |
|
2.3 (2025-06-07) |
Many expired deprecations ( |
2.4 (2025-12-20) |
|
2.5 (2026-06-21) |
|
2.6 (upcoming) |
Planned removal of the mypy plugin, deprecation of |