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

flowchart TD A[Code on NumPy 1.26] --> B[Run Ruff NPY201 and apply the safe fixes] B --> C[Install NumPy 2.5 and run the tests with warnings as errors] C --> D{Failures?} D -- promotion or overflow --> E[Review NEP 50 cases] D -- removed names --> F[Use the replacement table] D -- compiled extensions --> G[Rebuild against NumPy 2, see the C-API page] E --> H[Pin the supported range and test the oldest and newest NumPy] F --> H G --> H
Figure 1. Migration plan from NumPy 1.x to the current release
  1. Work on NumPy 1.26 first and fix every deprecation warning. Removals are announced a release ahead.

  2. Run Ruff’s NPY201 rule and apply the safe fixes.

  3. Upgrade, run your tests with warnings turned into errors, and fix what remains.

  4. 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.

  5. Decide the supported range (for example numpy>=1.26,<3 or numpy>=2.0) and test the oldest and newest versions in your continuous integration.

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

np.float_, np.complex_, np.cfloat

np.float64, np.complex128

np.longfloat, np.longcomplex, np.clongfloat

np.longdouble, np.clongdouble

np.singlecomplex

np.complex64

np.string_, np.unicode_

np.bytes_, np.str_

np.NaN

np.nan

np.Inf, np.Infinity, np.infty, np.PINF

np.inf

np.NINF

-np.inf

np.NZERO, np.PZERO

-0.0, 0.0

np.alltrue, np.sometrue

np.all, np.any

np.product, np.cumproduct, np.round_

np.prod, np.cumprod, np.round

np.asfarray

np.asarray(x, dtype=float)

np.cast

np.asarray(arr, dtype=dtype)

np.find_common_type

np.promote_types or np.result_type

np.geterrobj, np.seterrobj

the np.errstate context manager

np.mat

np.asmatrix (but see the matrix note below)

np.recfromcsv, np.recfromtxt

np.genfromtxt

np.fastCopyAndTranspose

arr.T.copy()

np.issubsctype, np.obj2sctype, np.sctype2char, np.maximum_sctype

np.issubdtype, np.dtype(obj).type, np.dtype(obj).char, an explicit dtype

np.safe_eval

ast.literal_eval

np.who, np.disp, np.source, np.lookfor

an IDE, your own printing function, inspect.getsource, the documentation search

ndarray.ptp() method, ndarray.newbyteorder()

np.ptp(arr), arr.view(arr.dtype.newbyteorder(order))

np.core

private: it became np._core; use the public namespaces

Other namespace changes in 2.0:

  • np.lib now contains only a short list (for example array_utils, format, mixins, npyio, scimath, stride_tricks, NumpyVersion). Functions that used to be reachable as np.lib.xxx live in the main namespace.

  • numpy.strings is a new namespace of string ufuncs. Prefer it to numpy.char; in 2.5 numpy.char.chararray and numpy.char.array are deprecated.

  • numpy.array_api was removed; the main namespace follows the array API standard instead (see The Array API Standard).

  • np.exceptions holds AxisError, ComplexWarning, VisibleDeprecationWarning and 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)

np.tostring, np.compat source code, fromstring binary mode

tobytes, drop the import, frombuffer

2.4 (2025-12-20)

np.trapz

np.trapezoid (or scipy.integrate)

2.4

np.in1d

np.isin

2.4

interpolation= in percentile, quantile and the nan versions

method=

2.4

reshape(newshape=...)

reshape(shape)

2.4

np.sum(generator) (now a TypeError)

sum(generator) or np.sum(np.fromiter(...))

2.5 (2026-06-21)

np.row_stack

np.vstack

2.5

numpy.distutils

Meson, meson-python, setuptools, CMake

2.5

the 'a' dtype alias

'S'

2.5

recfromtxt and recfromcsv re-exports

np.genfromtxt

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

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.

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.eig and eigvals always return complex arrays from NumPy 2.5; before they returned a real array when all eigenvalues were real. Use eigh or eigvalsh for symmetric or Hermitian matrices, which return real values. To keep the old behaviour: w = eigvals(a), then if np.any(w.imag == 0): w = w.real, exactly as the release notes show.

  • vecdot, matrix_transpose, .mT, matrix_norm, vector_norm and svdvals are new in 2.0; matvec and vecmat arrived in 2.2. lstsq changed the default of rcond and solve changed its broadcasting rules in 2.0. In 2.5.4, svd and lstsq raise for inputs with infinities instead of returning garbage.

  • numpy.cov with a single-row matrix and rowvar=False returns an array, not a scalar (2.2). Norms of empty arrays return zero (2.3).

  • np.histogram automatic 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

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.

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.

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

np.random.seed(0), np.random.rand, np.random.randn, np.random.randint at module level

Called "discouraged" in the random documentation; the legacy RandomState stream is frozen

rng = np.random.default_rng(0), then rng.random, rng.standard_normal, rng.integers. Use SeedSequence.spawn for parallel work.

np.random.RandomState(seed) in new code

Legacy generator, kept only for stream compatibility

np.random.default_rng(seed)

np.float_, np.complex_, np.NaN, np.Inf, np.infty, np.string_, np.unicode_

Removed in 2.0 (2024-06-16)

np.float64, np.complex128, np.nan, np.inf, np.bytes_, np.str_

np.product, np.cumproduct, np.alltrue, np.sometrue, np.round_, np.asfarray, np.cast, np.mat

Removed in 2.0

np.prod, np.cumprod, np.all, np.any, np.round, np.asarray(x, dtype=float), np.asarray, np.array

np.trapz, np.in1d, interpolation= in percentile, reshape(newshape=...)

Removed in 2.4 (2025-12-20)

np.trapezoid, np.isin, method=, reshape(shape)

np.row_stack, numpy.distutils, the 'a' dtype alias, recfromcsv

Removed in 2.5 (2026-06-21)

np.vstack, Meson or setuptools, 'S', np.genfromtxt

np.array(x, copy=False) to avoid a copy

copy=False now raises when a copy is needed (2.0)

np.asarray(x) or copy=None

Results printed as 3.0 or array([1., 2.])[0] giving 1.0 in doctests

Scalar repr includes the type (2.0, NEP 51)

Expect np.float64(3.0); use str() or print for plain text, or legacy="1.25" temporarily

np.float32(3) + 3.0 giving float64, or scalar value-based promotion

NEP 50 (2.0): Python scalars are weak

Read Type Promotion (NEP 50); cast explicitly

Default integer int32 on Windows

int64 since 2.0

Pass dtype explicitly when a compiled library expects long

np.core, np.lib.xxx for functions now in the main namespace

np.core became private np._core (2.0)

Use public names

np.matrix, np.mat for linear algebra

"No longer recommended" (and np.mat removed in 2.0)

2-D ndarray and @

np.poly1d, np.polyfit for new code

Legacy API

numpy.polynomial.Polynomial.fit (see Polynomials)

np.char.* and chararray for string work

numpy.strings since 2.0; chararray deprecated in 2.5

np.strings or StringDType

Eigenvalues of real matrices returned as a real array

eig and eigvals always return complex since 2.5

eigh and eigvalsh for symmetric input, or take .real deliberately

arr.shape = ..., arr.dtype = ..., arr.strides = ...

Deprecated in 2.4 and 2.5

reshape, view, np.lib.stride_tricks

from numpy.distutils.core import setup for Fortran

Removed in 2.5

python -m numpy.f2py -c ..., Meson

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

np.random.seed and randn at module level, .values in place of to_numpy(). The array chapters (ndarray, indexing, ufuncs, strides, structured arrays) remain valid ideas. A 3rd edition (2022) exists and is free to read online.

Géron, Hands-On Machine Learning with Scikit-Learn and TensorFlow (2017)

scikit-learn 0.18, TensorFlow 1

np.random.seed; TensorFlow 1 session code. Read for ideas only.

Géron, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (2nd edition, 2019; early release)

scikit-learn 0.20, TensorFlow 2

np.infty (removed in 2.0), np.random.seed.

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 default_rng. It predates NumPy 2.4 and 2.5 changes such as the removal of np.trapz and the scalar repr.

Marsland, Machine Learning: An Algorithmic Perspective (2nd edition, 2015)

Python 2, NumPy 1.x, pylab

print statements, integer division and import pylab. The from-scratch NumPy algorithms are useful once ported.

LazyProgrammer, Deep Learning in Python (2016)

Python 2, Theano, TensorFlow 1

xrange, print x, Theano and TensorFlow 1 APIs. Only the short NumPy back-propagation sketch is of lasting use.

Skansi, Introduction to Deep Learning (2018)

Python 3.5 and 3.6, Keras 2

An unseeded np.random.rand mask for a train and test split instead of a seeded generator or train_test_split.

Moroney, AI and ML for Coders in PyTorch (2025)

PyTorch 2

np.random.RandomState for random data; use default_rng.

Igual and Seguí, Introduction to Data Science (1st edition, 2017)

Python 2.7, pandas 0.18

Python 2 print. A 2nd edition appeared in 2024.

Hunt, Advanced Guide to Python 3 Programming (2019)

Python 3.7, Matplotlib 3

np.polyfit for curve fitting (use numpy.polynomial); its 3D plot calls changed in Matplotlib 3.6.

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, copy keyword, StringDType, numpy.strings, C ABI break, np.core private

2.1 (2024-08-18)

copyto and full treat Python scalars as safe casts; floor, ceil and trunc keep integer dtypes; C-API symbols hidden; fix_imports of np.save deprecated

2.2 (2024-12-08)

bool of an empty array raises; cov single-row fix; NEP 50 escape hatch removed

2.3 (2025-06-07)

Many expired deprecations (tostring, compat, minlength=None, …​); mypy_plugin and NBitBase deprecated; manylinux_2_28 wheels; array API 2024.12

2.4 (2025-12-20)

trapz, in1d, interpolation=, newshape= removed; round always copies; strides setter deprecated; where= without out= warns

2.5 (2026-06-21)

distutils and row_stack removed; eig always complex; chararray, fix and setting shape or dtype deprecated; Python 3.11 dropped; Cython 3 required for the headers

2.6 (upcoming)

Planned removal of the mypy plugin, deprecation of np.dot with more than 2 dimensions on the right; see the what’s-new page