chore(deps): update dependency numpy to v2 #40
Loading…
x
Reference in New Issue
Block a user
No description provided.
Delete Branch "renovate/numpy-2.x"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
This PR contains the following updates:
1.22.3
->2.3.1
Release Notes
numpy/numpy
v2.3.1
Compare Source
NumPy 2.3.1 Release Notes
The NumPy 2.3.1 release is a patch release with several bug fixes,
annotation improvements, and better support for OpenBSD. Highlights are:
matmul
for non-contiguous out kwarg parameternp.vectorize
casting errorsThis release supports Python versions 3.11-3.13, Python 3.14 will be
supported when it is released.
Contributors
A total of 9 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 12 pull requests were merged for this release.
np.vectorize
casting to legacy behavior (#29196)Checksums
MD5
SHA256
v2.3.0
Compare Source
NumPy 2.3.0 Release Notes
The NumPy 2.3.0 release continues the work to improve free threaded
Python support and annotations together with the usual set of bug fixes.
It is unusual in the number of expired deprecations, code
modernizations, and style cleanups. The latter may not be visible to
users, but is important for code maintenance over the long term. Note
that we have also upgraded from manylinux2014 to manylinux_2_28.
Users running on a Mac having an M4 cpu might see various warnings about
invalid values and such. The warnings are a known problem with
Accelerate. They are annoying, but otherwise harmless. Apple promises to
fix them.
This release supports Python versions 3.11-3.13, Python 3.14 will be
supported when it is released.
Highlights
New functions
New function
numpy.strings.slice
The new function
numpy.strings.slice
was added, which implements fastnative slicing of string arrays. It supports the full slicing API
including negative slice offsets and steps.
(gh-27789)
Deprecations
The
numpy.typing.mypy_plugin
has been deprecated in favor ofplatform-agnostic static type inference. Please remove
numpy.typing.mypy_plugin
from theplugins
section of your mypyconfiguration. If this change results in new errors being reported,
kindly open an issue.
(gh-28129)
The
numpy.typing.NBitBase
type has been deprecated and will beremoved in a future version.
This type was previously intended to be used as a generic upper
bound for type-parameters, for example:
But in NumPy 2.2.0,
float64
andcomplex128
were changed toconcrete subtypes, causing static type-checkers to reject
x: np.float64 = f(np.complex128(42j))
.So instead, the better approach is to use
typing.overload
:(gh-28884)
Expired deprecations
Remove deprecated macros like
NPY_OWNDATA
from Cython interfacesin favor of
NPY_ARRAY_OWNDATA
(deprecated since 1.7)(gh-28254)
Remove
numpy/npy_1_7_deprecated_api.h
and C macros likeNPY_OWNDATA
in favor ofNPY_ARRAY_OWNDATA
(deprecated since 1.7)(gh-28254)
Remove alias
generate_divbyzero_error
tonpy_set_floatstatus_divbyzero
andgenerate_overflow_error
tonpy_set_floatstatus_overflow
(deprecated since 1.10)(gh-28254)
Remove
np.tostring
(deprecated since 1.19)(gh-28254)
Raise on
np.conjugate
of non-numeric types (deprecated since 1.13)(gh-28254)
Raise when using
np.bincount(...minlength=None)
, use 0 instead(deprecated since 1.14)
(gh-28254)
Passing
shape=None
to functions with a non-optional shape argumenterrors, use
()
instead (deprecated since 1.20)(gh-28254)
Inexact matches for
mode
andsearchside
raise (deprecated since1.20)
(gh-28254)
Setting
__array_finalize__ = None
errors (deprecated since 1.23)(gh-28254)
np.fromfile
andnp.fromstring
error on bad data, previously theywould guess (deprecated since 1.18)
(gh-28254)
datetime64
andtimedelta64
construction with a tuple no longeraccepts an
event
value, either use a two-tuple of (unit, num) or a4-tuple of (unit, num, den, 1) (deprecated since 1.14)
(gh-28254)
When constructing a
dtype
from a class with adtype
attribute,that attribute must be a dtype-instance rather than a thing that can
be parsed as a dtype instance (deprecated in 1.19). At some point
the whole construct of using a dtype attribute will be deprecated
(see #25306)
(gh-28254)
Passing booleans as partition index errors (deprecated since 1.23)
(gh-28254)
Out-of-bounds indexes error even on empty arrays (deprecated since
1.20)
(gh-28254)
np.tostring
has been removed, usetobytes
instead (deprecatedsince 1.19)
(gh-28254)
Disallow make a non-writeable array writeable for arrays with a base
that do not own their data (deprecated since 1.17)
(gh-28254)
concatenate()
withaxis=None
usessame-kind
casting bydefault, not
unsafe
(deprecated since 1.20)(gh-28254)
Unpickling a scalar with object dtype errors (deprecated since 1.20)
(gh-28254)
The binary mode of
fromstring
now errors, usefrombuffer
instead(deprecated since 1.14)
(gh-28254)
Converting
np.inexact
ornp.floating
to a dtype errors(deprecated since 1.19)
(gh-28254)
Converting
np.complex
,np.integer
,np.signedinteger
,np.unsignedinteger
,np.generic
to a dtype errors (deprecatedsince 1.19)
(gh-28254)
The Python built-in
round
errors for complex scalars. Usenp.round
orscalar.round
instead (deprecated since 1.19)(gh-28254)
'np.bool' scalars can no longer be interpreted as an index
(deprecated since 1.19)
(gh-28254)
Parsing an integer via a float string is no longer supported.
(deprecated since 1.23) To avoid this error you can
converters=float
keyword argument.np.loadtxt(...).astype(np.int64)
(gh-28254)
The use of a length 1 tuple for the ufunc
signature
errors. Usedtype
or fill the tuple withNone
(deprecated since 1.19)(gh-28254)
Special handling of matrix is in np.outer is removed. Convert to a
ndarray via
matrix.A
(deprecated since 1.20)(gh-28254)
Removed the
np.compat
package source code (removed in 2.0)(gh-28961)
C API changes
NpyIter_GetTransferFlags
is now available to check if the iteratorneeds the Python API or if casts may cause floating point errors
(FPE). FPEs can for example be set when casting
float64(1e300)
tofloat32
(overflow to infinity) or a NaN to an integer (invalidvalue).
(gh-27883)
NpyIter
now has no limit on the number of operands it supports.(gh-28080)
New
NpyIter_GetTransferFlags
andNpyIter_IterationNeedsAPI
changeNumPy now has the new
NpyIter_GetTransferFlags
function as a moreprecise way checking of iterator/buffering needs. I.e. whether the
Python API/GIL is required or floating point errors may occur. This
function is also faster if you already know your needs without
buffering.
The
NpyIter_IterationNeedsAPI
function now performs all the checksthat were previously performed at setup time. While it was never
necessary to call it multiple times, doing so will now have a larger
cost.
(gh-27998)
New Features
The type parameter of
np.dtype
now defaults totyping.Any
. Thisway, static type-checkers will infer
dtype: np.dtype
asdtype: np.dtype[Any]
, without reporting an error.(gh-28669)
Static type-checkers now interpret:
_: np.ndarray
as_: npt.NDArray[typing.Any]
._: np.flatiter
as_: np.flatiter[np.ndarray]
.This is because their type parameters now have default values.
(gh-28940)
NumPy now registers its pkg-config paths with the pkgconf PyPI package
The pkgconf PyPI
package provides an interface for projects like NumPy to register their
own paths to be added to the pkg-config search path. This means that
when using pkgconf
from PyPI, NumPy will be discoverable without needing for any custom
environment configuration.
(gh-28214)
Allow
out=...
in ufuncs to ensure array resultNumPy has the sometimes difficult behavior that it currently usually
returns scalars rather than 0-D arrays (even if the inputs were 0-D
arrays). This is especially problematic for non-numerical dtypes (e.g.
object
).For ufuncs (i.e. most simple math functions) it is now possible to use
out=...
(literally `...`, e.g.out=Ellipsis
) which is identicalin behavior to
out
not being passed, but will ensure a non-scalarreturn. This spelling is borrowed from
arr1d[0, ...]
where the...
also ensures a non-scalar return.
Other functions with an
out=
kwarg should gain support eventually.Downstream libraries that interoperate via
__array_ufunc__
or__array_function__
may need to adapt to support this.(gh-28576)
Building NumPy with OpenMP Parallelization
NumPy now supports OpenMP parallel processing capabilities when built
with the
-Denable_openmp=true
Meson build flag. This feature isdisabled by default. When enabled,
np.sort
andnp.argsort
functionscan utilize OpenMP for parallel thread execution, improving performance
for these operations.
(gh-28619)
Interactive examples in the NumPy documentation
The NumPy documentation includes a number of examples that can now be
run interactively in your browser using WebAssembly and Pyodide.
Please note that the examples are currently experimental in nature and
may not work as expected for all methods in the public API.
(gh-26745)
Improvements
Scalar comparisons between non-comparable dtypes such as
np.array(1) == np.array('s')
now return a NumPy bool instead of aPython bool.
(gh-27288)
np.nditer
now has no limit on the number of supported operands(C-integer).
(gh-28080)
No-copy pickling is now supported for any array that can be
transposed to a C-contiguous array.
(gh-28105)
The
__repr__
for user-defined dtypes now prefers the__name__
ofthe custom dtype over a more generic name constructed from its
kind
anditemsize
.(gh-28250)
np.dot
now reports floating point exceptions.(gh-28442)
np.dtypes.StringDType
is now a generictype which
accepts a type argument for
na_object
that defaults totyping.Never
. For example,StringDType(na_object=None)
returns aStringDType[None]
, andStringDType()
returns aStringDType[typing.Never]
.(gh-28856)
Added warnings to
np.isclose
Added warning messages if at least one of atol or rtol are either
np.nan
ornp.inf
withinnp.isclose
.np.seterr
settings(gh-28205)
Performance improvements and changes
Performance improvements to
np.unique
np.unique
now tries to use a hash table to find unique values insteadof sorting values before finding unique values. This is limited to
certain dtypes for now, and the function is now faster for those dtypes.
The function now also exposes a
sorted
parameter to allow returningunique values as they were found, instead of sorting them afterwards.
(gh-26018)
Performance improvements to
np.sort
andnp.argsort
np.sort
andnp.argsort
functions now can leverage OpenMP forparallel thread execution, resulting in up to 3.5x speedups on x86
architectures with AVX2 or AVX-512 instructions. This opt-in feature
requires NumPy to be built with the -Denable_openmp Meson flag. Users
can control the number of threads used by setting the OMP_NUM_THREADS
environment variable.
(gh-28619)
Performance improvements for
np.float16
castsEarlier, floating point casts to and from
np.float16
types wereemulated in software on all platforms.
Now, on ARM devices that support Neon float16 intrinsics (such as recent
Apple Silicon), the native float16 path is used to achieve the best
performance.
(gh-28769)
Changes
The vector norm
ord=inf
and the matrix normsord={1, 2, inf, 'nuc'}
now always returns zero for empty arrays.Empty arrays have at least one axis of size zero. This affects
np.linalg.norm
,np.linalg.vector_norm
, andnp.linalg.matrix_norm
. Previously, NumPy would raises errors orreturn zero depending on the shape of the array.
(gh-28343)
A spelling error in the error message returned when converting a
string to a float with the method
np.format_float_positional
hasbeen fixed.
(gh-28569)
NumPy's
__array_api_version__
was upgraded from2023.12
to2024.12
.numpy.count_nonzero
foraxis=None
(default) now returns a NumPyscalar instead of a Python integer.
The parameter
axis
innumpy.take_along_axis
function has now adefault value of
-1
.(gh-28615)
Printing of
np.float16
andnp.float32
scalars and arrays havebeen improved by adjusting the transition to scientific notation
based on the floating point precision. A new legacy
np.printoptions
mode'2.2'
has been added for backwardscompatibility.
(gh-28703)
Multiplication between a string and integer now raises OverflowError
instead of MemoryError if the result of the multiplication would
create a string that is too large to be represented. This follows
Python's behavior.
(gh-29060)
unique_values
may return unsorted dataThe relatively new function (added in NumPy 2.0)
unique_values
may nowreturn unsorted results. Just as
unique_counts
andunique_all
thesenever guaranteed a sorted result, however, the result was sorted until
now. In cases where these do return a sorted result, this may change in
future releases to improve performance.
(gh-26018)
Changes to the main iterator and potential numerical changes
The main iterator, used in math functions and via
np.nditer
fromPython and
NpyIter
in C, now behaves differently for some bufferediterations. This means that:
sized allowed by the
buffersize
parameter.no operand requires buffering.
For
np.sum()
such changes in buffersize may slightly change numericalresults of floating point operations. Users who use "growinner" for
custom reductions could notice changes in precision (for example, in
NumPy we removed it from
einsum
to avoid most precision changes andimprove precision for some 64bit floating point inputs).
(gh-27883)
The minimum supported GCC version is now 9.3.0
The minimum supported version was updated from 8.4.0 to 9.3.0, primarily
in order to reduce the chance of platform-specific bugs in old GCC
versions from causing issues.
(gh-28102)
Changes to automatic bin selection in numpy.histogram
The automatic bin selection algorithm in
numpy.histogram
has beenmodified to avoid out-of-memory errors for samples with low variation.
For full control over the selected bins the user can use set the
bin
or
range
parameters ofnumpy.histogram
.(gh-28426)
Build manylinux_2_28 wheels
Wheels for linux systems will use the
manylinux_2_28
tag (instead ofthe
manylinux2014
tag), which means dropping support forredhat7/centos7, amazonlinux2, debian9, ubuntu18.04, and other
pre-glibc2.28 operating system versions, as per the PEP 600 support
table.
(gh-28436)
Remove use of -Wl,-ld_classic on macOS
Remove use of -Wl,-ld_classic on macOS. This hack is no longer needed by
Spack, and results in libraries that cannot link to other libraries
built with ld (new).
(gh-28713)
Re-enable overriding functions in the
numpy.strings
Re-enable overriding functions in the
numpy.strings
module.(gh-28741)
Checksums
MD5
SHA256
v2.2.6
Compare Source
NumPy 2.2.6 Release Notes
NumPy 2.2.6 is a patch release that fixes bugs found after the 2.2.5
release. It is a mix of typing fixes/improvements as well as the normal
bug fixes and some CI maintenance.
This release supports Python versions 3.10-3.13.
Contributors
A total of 8 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 11 pull requests were merged for this release.
NDArray[floating] + float
return typeCanIndex
annotation inndarray.setfield
Checksums
MD5
SHA256
v2.2.5
Compare Source
NumPy 2.2.5 Release Notes
NumPy 2.2.5 is a patch release that fixes bugs found after the 2.2.4
release. It has a large number of typing fixes/improvements as well as
the normal bug fixes and some CI maintenance.
This release supports Python versions 3.10-3.13.
Contributors
A total of 7 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 19 pull requests were merged for this release.
_core.strings
ndarray.tolist()
and.item()
for unknown dtypewrite()
tostr
insavetxt
"b1"
literals fordtype[bool]
NDArray[object_].__abs__()
NDArray[float64].__[r]truediv__
return...ndarray
rich comparison operators[arg]partition
fixesrandom.Generator.integers
return typecount_nonzero
signatureChecksums
MD5
SHA256
v2.2.4
Compare Source
NumPy 2.2.4 Release Notes
NumPy 2.2.4 is a patch release that fixes bugs found after the 2.2.3
release. There are a large number of typing improvements, the rest of
the changes are the usual mix of bugfixes and platform maintenace.
This release supports Python versions 3.10-3.13.
Contributors
A total of 15 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 17 pull requests were merged for this release.
__array_interface__
number of dimensionsChecksums
MD5
SHA256
v2.2.3
Compare Source
NumPy 2.2.3 Release Notes
NumPy 2.2.3 is a patch release that fixes bugs found after the 2.2.2
release. The majority of the changes are typing improvements and fixes
for free threaded Python. Both of those areas are still under
development, so if you discover new problems, please report them.
This release supports Python versions 3.10-3.13.
Contributors
A total of 9 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 21 pull requests were merged for this release.
from_float_positional
errors for huge padsfloat64
in the set-opstimedelta64.__divmod__
andtimedelta64.__mod__
...numpy.matlib
numpy.testing
modulesTYP:
PR's and issuesChecksums
MD5
SHA256
v2.2.2
Compare Source
NumPy 2.2.2 Release Notes
NumPy 2.2.2 is a patch release that fixes bugs found after the 2.2.1
release. The number of typing fixes/updates is notable. This release
supports Python versions 3.10-3.13.
Contributors
A total of 8 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 16 pull requests were merged for this release.
void
arrays not acceptingstr
keys in__setitem__
integer
binop return types (#28065)ndarray
binop return types forfloat64
&...bool
fromissubdtype
date[time]
in thedatetime64
constructorinterp
to accept and return scalarsChecksums
MD5
SHA256
v2.2.1
Compare Source
NumPy 2.2.1 Release Notes
NumPy 2.2.1 is a patch release following 2.2.0. It fixes bugs found
after the 2.2.0 release and has several maintenance pins to work around
upstream changes.
There was some breakage in downstream projects following the 2.2.0
release due to updates to NumPy typing. Because of problems due to MyPy
defects, we recommend using basedpyright for type checking, it can be
installed from PyPI. The Pylance extension for Visual Studio Code is
also based on Pyright. Problems that persist when using basedpyright
should be reported as issues on the NumPy github site.
This release supports Python 3.10-3.13.
Contributors
A total of 9 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 12 pull requests were merged for this release.
ndarray.__setitem__
#include <Python.h>
withextern "C"
None
in operand sequence of nditerChecksums
MD5
SHA256
v2.2.0
Compare Source
NumPy 2.2.0 Release Notes
The NumPy 2.2.0 release is quick release that brings us back into sync
with the usual twice yearly release cycle. There have been an number of
small cleanups, as well as work bringing the new StringDType to
completion and improving support for free threaded Python. Highlights
are:
matvec
andvecmat
, see below.This release supports Python versions 3.10-3.13.
Deprecations
_add_newdoc_ufunc
is now deprecated.ufunc.__doc__ = newdoc
should be used instead.
(gh-27735)
Expired deprecations
bool(np.array([]))
and other empty arrays will now raise an error.Use
arr.size > 0
instead to check whether an array has noelements.
(gh-27160)
Compatibility notes
numpy.cov
now properly transposes single-row (2darray) design matrices when
rowvar=False
. Previously, single-rowdesign matrices would return a scalar in this scenario, which is not
correct, so this is a behavior change and an array of the
appropriate shape will now be returned.
(gh-27661)
New Features
New functions for matrix-vector and vector-matrix products
Two new generalized ufuncs were defined:
numpy.matvec
- matrix-vector product, treating thearguments as stacks of matrices and column vectors,
respectively.
numpy.vecmat
- vector-matrix product, treating thearguments as stacks of column vectors and matrices,
respectively. For complex vectors, the conjugate is taken.
These add to the existing
numpy.matmul
as well as tonumpy.vecdot
, which was added in numpy 2.0.Note that
numpy.matmul
never takes a complexconjugate, also not when its left input is a vector, while both
numpy.vecdot
andnumpy.vecmat
do takethe conjugate for complex vectors on the left-hand side (which are
taken to be the ones that are transposed, following the physics
convention).
(gh-25675)
np.complexfloating[T, T]
can now also be written asnp.complexfloating[T]
(gh-27420)
UFuncs now support
__dict__
attribute and allow overriding__doc__
(either directly or viaufunc.__dict__["__doc__"]
).__dict__
can be used to also override other properties, such as__module__
or__qualname__
.(gh-27735)
The "nbit" type parameter of
np.number
and its subtypes nowdefaults to
typing.Any
. This way, type-checkers will inferannotations such as
x: np.floating
asx: np.floating[Any]
, evenin strict mode.
(gh-27736)
Improvements
The
datetime64
andtimedelta64
hashes now correctly match thePythons builtin
datetime
andtimedelta
ones. The hashes nowevaluated equal even for equal values with different time units.
(gh-14622)
Fixed a number of issues around promotion for string ufuncs with
StringDType arguments. Mixing StringDType and the fixed-width DTypes
using the string ufuncs should now generate much more uniform
results.
(gh-27636)
Improved support for empty
memmap
. Previously an emptymemmap
would fail unless a non-zerooffset
was set.Now a zero-size
memmap
is supported even ifoffset=0
. To achieve this, if amemmap
is mapped toan empty file that file is padded with a single byte.
(gh-27723)
A regression has been fixed which allows F2PY users to expose variables
to Python in modules with only assignments, and also fixes situations
where multiple modules are present within a single source file.
(gh-27695)
Performance improvements and changes
Improved multithreaded scaling on the free-threaded build when many
threads simultaneously call the same ufunc operations.
(gh-27896)
NumPy now uses fast-on-failure attribute lookups for protocols. This
can greatly reduce overheads of function calls or array creation
especially with custom Python objects. The largest improvements will
be seen on Python 3.12 or newer.
(gh-27119)
OpenBLAS on x86_64 and i686 is built with fewer kernels. Based on
benchmarking, there are 5 clusters of performance around these
kernels:
PRESCOTT NEHALEM SANDYBRIDGE HASWELL SKYLAKEX
.OpenBLAS on windows is linked without quadmath, simplifying
licensing
Due to a regression in OpenBLAS on windows, the performance
improvements when using multiple threads for OpenBLAS 0.3.26 were
reverted.
(gh-27147)
NumPy now indicates hugepages also for large
np.zeros
allocationson linux. Thus should generally improve performance.
(gh-27808)
Changes
numpy.fix
now won't perform casting to a floatingdata-type for integer and boolean data-type input arrays.
(gh-26766)
The type annotations of
numpy.float64
andnumpy.complex128
nowreflect that they are also subtypes of the built-in
float
andcomplex
types, respectively. This update prevents statictype-checkers from reporting errors in cases such as:
(gh-27334)
The
repr
of arrays large enough to be summarized (i.e., whereelements are replaced with
...
) now includes theshape
of thearray, similar to what already was the case for arrays with zero
size and non-obvious shape. With this change, the shape is always
given when it cannot be inferred from the values. Note that while
written as
shape=...
, this argument cannot actually be passed into the
np.array
constructor. If you encounter problems, e.g., dueto failing doctests, you can use the print option
legacy=2.1
toget the old behaviour.
(gh-27482)
Calling
__array_wrap__
directly on NumPy arrays or scalars nowdoes the right thing when
return_scalar
is passed (Added in NumPy2). It is further safe now to call the scalar
__array_wrap__
on anon-scalar result.
(gh-27807)
Bump the musllinux CI image and wheels to 1_2 from 1_1. This is because
1_1 is end of life.
(gh-27088)
The NEP 50 promotion state settings are now removed. They were always
meant as temporary means for testing. A warning will be given if the
environment variable is set to anything but
NPY_PROMOTION_STATE=weak
while
_set_promotion_state
and_get_promotion_state
are removed. Incase code used
_no_nep50_warning
, acontextlib.nullcontext
could beused to replace it when not available.
(gh-27156)
Checksums
MD5
SHA256
v2.1.3
Compare Source
NumPy 2.1.3 Release Notes
NumPy 2.1.3 is a maintenance release that fixes bugs and regressions
discovered after the 2.1.2 release. This release also adds support
for free threaded Python 3.13 on Windows.
The Python versions supported by this release are 3.10-3.13.
Improvements
Fixed a number of issues around promotion for string ufuncs with
StringDType arguments. Mixing StringDType and the fixed-width DTypes
using the string ufuncs should now generate much more uniform
results.
(gh-27636)
Changes
numpy.fix
now won't perform casting to a floatingdata-type for integer and boolean data-type input arrays.
(gh-26766)
Contributors
A total of 15 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 21 pull requests were merged for this release.
python
to 3.12 in environment.ymlChecksums
MD5
SHA256
v2.1.2
Compare Source
NumPy 2.1.2 Release Notes
NumPy 2.1.2 is a maintenance release that fixes bugs and regressions
discovered after the 2.1.1 release.
The Python versions supported by this release are 3.10-3.13.
Contributors
A total of 11 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 14 pull requests were merged for this release.
Checksums
MD5
SHA256
v2.1.1
Compare Source
NumPy 2.1.1 Release Notes
NumPy 2.1.1 is a maintenance release that fixes bugs and regressions
discovered after the 2.1.0 release.
The Python versions supported by this release are 3.10-3.13.
Contributors
A total of 7 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 10 pull requests were merged for this release.
Checksums
MD5
SHA256
v2.1.0
Compare Source
NumPy 2.1.0 Release Notes
NumPy 2.1.0 provides support for the upcoming Python 3.13 release and
drops support for Python 3.9. In addition to the usual bug fixes and
updated Python support, it helps get us back into our usual release
cycle after the extended development of 2.0. The highlights for this
release are:
Python versions 3.10-3.13 are supported in this release.
New functions
New function
numpy.unstack
A new function
np.unstack(array, axis=...)
was added, which splits anarray into a tuple of arrays along an axis. It serves as the inverse of
[numpy.stack]{.title-ref}.
(gh-26579)
Deprecations
The
fix_imports
keyword argument innumpy.save
is deprecated.Since NumPy 1.17,
numpy.save
uses a pickle protocol that no longersupports Python 2, and ignored
fix_imports
keyword. This keywordis kept only for backward compatibility. It is now deprecated.
(gh-26452)
Passing non-integer inputs as the first argument of
[bincount]{.title-ref} is now deprecated, because such inputs are
silently cast to integers with no warning about loss of precision.
(gh-27076)
Expired deprecations
Scalars and 0D arrays are disallowed for
numpy.nonzero
andnumpy.ndarray.nonzero
.(gh-26268)
set_string_function
internal function was removed andPyArray_SetStringFunction
was stubbed out.(gh-26611)
C API changes
API symbols now hidden but customizable
NumPy now defaults to hide the API symbols it adds to allow all NumPy
API usage. This means that by default you cannot dynamically fetch the
NumPy API from another library (this was never possible on windows).
If you are experiencing linking errors related to
PyArray_API
orPyArray_RUNTIME_VERSION
, you can define theNPY_API_SYMBOL_ATTRIBUTE
to opt-out of this change.
If you are experiencing problems due to an upstream header including
NumPy, the solution is to make sure you
#include "numpy/ndarrayobject.h"
before their header and import NumPyyourself based on
including-the-c-api
.(gh-26103)
Many shims removed from npy_3kcompat.h
Many of the old shims and helper functions were removed from
npy_3kcompat.h
. If you find yourself in need of these, vendor theprevious version of the file into your codebase.
(gh-26842)
New
PyUFuncObject
fieldprocess_core_dims_func
The field
process_core_dims_func
was added to the structurePyUFuncObject
. For generalized ufuncs, this field can be set to afunction of type
PyUFunc_ProcessCoreDimsFunc
that will be called whenthe ufunc is called. It allows the ufunc author to check that core
dimensions satisfy additional constraints, and to set output core
dimension sizes if they have not been provided.
(gh-26908)
New Features
Preliminary Support for Free-Threaded CPython 3.13
CPython 3.13 will be available as an experimental free-threaded build.
See https://py-free-threading.github.io, PEP 703 and the
CPython 3.13 release notes for more detail about free-threaded Python.
NumPy 2.1 has preliminary support for the free-threaded build of CPython
3.13. This support was enabled by fixing a number of C thread-safety
issues in NumPy. Before NumPy 2.1, NumPy used a large number of C global
static variables to store runtime caches and other state. We have either
refactored to avoid the need for global state, converted the global
state to thread-local state, or added locking.
Support for free-threaded Python does not mean that NumPy is thread
safe. Read-only shared access to ndarray should be safe. NumPy exposes
shared mutable state and we have not added any locking to the array
object itself to serialize access to shared state. Care must be taken in
user code to avoid races if you would like to mutate the same array in
multiple threads. It is certainly possible to crash NumPy by mutating an
array simultaneously in multiple threads, for example by calling a ufunc
and the
resize
method simultaneously. For now our guidance is:"don't do that". In the future we would like to provide stronger
guarantees.
Object arrays in particular need special care, since the GIL previously
provided locking for object array access and no longer does. See
Issue #27199 for more information about object
arrays in the free-threaded build.
If you are interested in free-threaded Python, for example because you
have a multiprocessing-based workflow that you are interested in running
with Python threads, we encourage testing and experimentation.
If you run into problems that you suspect are because of NumPy, please
open an issue,
checking first if the bug also occurs in the "regular" non-free-threaded CPython 3.13
build. Many threading bugs can also occur in code that releases
the GIL; disabling the GIL only makes it easier to hit threading bugs.
(gh-26157)
f2py
can generate freethreading-compatible C extensionsPass
--freethreading-compatible
to the f2py CLI tool to produce a Cextension marked as compatible with the free threading CPython
interpreter. Doing so prevents the interpreter from re-enabling the GIL
at runtime when it imports the C extension. Note that
f2py
does notanalyze fortran code for thread safety, so you must verify that the
wrapped fortran code is thread safe before marking the extension as
compatible.
(gh-26981)
numpy.reshape
andnumpy.ndarray.reshape
now supportshape
andcopy
arguments.(gh-26292)
NumPy now supports DLPack v1, support for older versions will be
deprecated in the future.
(gh-26501)
numpy.asanyarray
now supportscopy
anddevice
arguments,matching
numpy.asarray
.(gh-26580)
numpy.printoptions
,numpy.get_printoptions
, andnumpy.set_printoptions
now support a new option,override_repr
,for defining custom
repr(array)
behavior.(gh-26611)
numpy.cumulative_sum
andnumpy.cumulative_prod
were added asArray API compatible alternatives for
numpy.cumsum
andnumpy.cumprod
. The new functions can include a fixed initial(zeros for
sum
and ones forprod
) in the result.(gh-26724)
numpy.clip
now supportsmax
andmin
keyword arguments whichare meant to replace
a_min
anda_max
. Also, fornp.clip(a)
ornp.clip(a, None, None)
a copy of the input array will be returnedinstead of raising an error.
(gh-26724)
numpy.astype
now supportsdevice
argument.(gh-26724)
Improvements
histogram
auto-binning now returns bin sizes >=1 for integer input dataFor integer input data, bin sizes smaller than 1 result in spurious
empty bins. This is now avoided when the number of bins is computed
using one of the algorithms provided by
histogram_bin_edges
.(gh-12150)
ndarray
shape-type parameter is now covariant and bound totuple[int, ...]
Static typing for
ndarray
is a long-term effort that continues withthis change. It is a generic type with type parameters for the shape and
the data type. Previously, the shape type parameter could be any value.
This change restricts it to a tuple of ints, as one would expect from
using
ndarray.shape
. Further, the shape-type parameter has beenchanged from invariant to covariant. This change also applies to the
subtypes of
ndarray
, e.g.numpy.ma.MaskedArray
. See thetyping docs
for more information.
(gh-26081)
np.quantile
with methodclosest_observation
chooses nearest even order statisticThis changes the definition of nearest for border cases from the nearest
odd order statistic to nearest even order statistic. The numpy
implementation now matches other reference implementations.
(gh-26656)
lapack_lite
is now thread safeNumPy provides a minimal low-performance version of LAPACK named
lapack_lite
that can be used if no BLAS/LAPACK system is detected atbuild time.
Until now,
lapack_lite
was not thread safe. Single-threaded use casesdid not hit any issues, but running linear algebra operations in
multiple threads could lead to errors, incorrect results, or segfaults
due to data races.
We have added a global lock, serializing access to
lapack_lite
inmultiple threads.
(gh-26750)
The
numpy.printoptions
context manager is now thread and async-safeIn prior versions of NumPy, the printoptions were defined using a
combination of Python and C global variables. We have refactored so the
state is stored in a python
ContextVar
, making the context managerthread and async-safe.
(gh-26846)
Type hinting
numpy.polynomial
Starting from the 2.1 release, PEP 484 type annotations have been
included for the functions and convenience classes in
numpy.polynomial
and its sub-packages.
(gh-26897)
Improved
numpy.dtypes
type hintsThe type annotations for
numpy.dtypes
are now a better reflection ofthe runtime: The
numpy.dtype
type-aliases have been replaced withspecialized
dtype
subtypes, and the previously missing annotationsfor
numpy.dtypes.StringDType
have been added.(gh-27008)
Performance improvements and changes
numpy.save
now uses pickle protocol version 4 for saving arrayswith object dtype, which allows for pickle objects larger than 4GB
and improves saving speed by about 5% for large arrays.
(gh-26388)
OpenBLAS on x86_64 and i686 is built with fewer kernels. Based on
benchmarking, there are 5 clusters of performance around these
kernels:
PRESCOTT NEHALEM SANDYBRIDGE HASWELL SKYLAKEX
.(gh-27147)
OpenBLAS on windows is linked without quadmath, simplifying
licensing
(gh-27147)
Due to a regression in OpenBLAS on windows, the performance
improvements when using multiple threads for OpenBLAS 0.3.26 were
reverted.
(gh-27147)
ma.cov
andma.corrcoef
are now significantly fasterThe private function has been refactored along with
ma.cov
andma.corrcoef
. They are now significantly faster, particularly on large,masked arrays.
(gh-26285)
Changes
As
numpy.vecdot
is now a ufunc it has a less precise signature.This is due to the limitations of ufunc's typing stub.
(gh-26313)
numpy.floor
,numpy.ceil
, andnumpy.trunc
now won't performcasting to a floating dtype for integer and boolean dtype input
arrays.
(gh-26766)
ma.corrcoef
may return a slightly different resultA pairwise observation approach is currently used in
ma.corrcoef
tocalculate the standard deviations for each pair of variables. This has
been changed as it is being used to normalise the covariance, estimated
using
ma.cov
, which does not consider the observations for eachvariable in a pairwise manner, rendering it unnecessary. The
normalisation has been replaced by the more appropriate standard
deviation for each variable, which significantly reduces the wall time,
but will return slightly different estimates of the correlation
coefficients in cases where the observations between a pair of variables
are not aligned. However, it will return the same estimates in all other
cases, including returning the same correlation matrix as
corrcoef
when using a masked array with no masked values.
(gh-26285)
Cast-safety fixes in
copyto
andfull
copyto
now uses NEP 50 correctly and applies this to its cast safety.Python integer to NumPy integer casts and Python float to NumPy float
casts are now considered "safe" even if assignment may fail or
precision may be lost. This means the following examples change
slightly:
np.copyto(int8_arr, 1000)
previously performed an unsafe/same-kind castof the Python integer. It will now always raise, to achieve an
unsafe cast you must pass an array or NumPy scalar.
np.copyto(uint8_arr, 1000, casting="safe")
will raise anOverflowError rather than a TypeError due to same-kind casting.
np.copyto(float32_arr, 1e300, casting="safe")
will overflow toinf
(float32 cannot hold1e300
) rather raising a TypeError.Further, only the dtype is used when assigning NumPy scalars (or 0-d
arrays), meaning that the following behaves differently:
np.copyto(float32_arr, np.float64(3.0), casting="safe")
raises.np.coptyo(int8_arr, np.int64(100), casting="safe")
raises.Previously, NumPy checked whether the 100 fits the
int8_arr
.This aligns
copyto
,full
, andfull_like
with the correct NumPy 2behavior.
(gh-27091)
Checksums
MD5
SHA256
v2.0.2
Compare Source
NumPy 2.0.2 Release Notes
NumPy 2.0.2 is a maintenance release that fixes bugs and regressions
discovered after the 2.0.1 release.
The Python versions supported by this release are 3.9-3.12.
Contributors
A total of 13 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 19 pull requests were merged for this release.
alltrue
andsometrue
npyv_loadable_stride_
functions for ldexp and...np.save
Checksums
MD5
SHA256
v2.0.1
Compare Source
NumPy 2.0.1 Release Notes
NumPy 2.0.1 is a maintenance release that fixes bugs and regressions
discovered after the 2.0.0 release. NumPy 2.0.1 is the last planned
release in the 2.0.x series, 2.1.0rc1 should be out shortly.
The Python versions supported by this release are 3.9-3.12.
NOTE: Do not use the GitHub generated "Source code" files listed in the "Assets", they are garbage.
Improvements
np.quantile
with methodclosest_observation
chooses nearest even order statisticThis changes the definition of nearest for border cases from the nearest
odd order statistic to nearest even order statistic. The numpy
implementation now matches other reference implementations.
(gh-26656)
Contributors
A total of 15 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 24 pull requests were merged for this release.
ma/extras.pyi
stubset_printoptions
loadtxt
PyArray_FillWithScalar
Checksums
MD5
SHA256
v2.0.0
Compare Source
NumPy 2.0.0 Release Notes
NumPy 2.0.0 is the first major release since 2006. It is the result of
11 months of development since the last feature release and is the work
of 212 contributors spread over 1078 pull requests. It contains a large
number of exciting new features as well as changes to both the Python
and C APIs.
This major release includes breaking changes that could not happen in a
regular minor (feature) release - including an ABI break, changes to
type promotion rules, and API changes which may not have been emitting
deprecation warnings in 1.26.x. Key documents related to how to adapt to
changes in NumPy 2.0, in addition to these release notes, include:
Highlights
Highlights of this release include:
numpy.dtypes.StringDType
and a newnumpy.strings
namespace with performant ufuncs for string operations,float32
andlongdouble
in allnumpy.fft
functions,numpy
namespace.
sort
,argsort
,partition
,argpartition
have beenaccelerated through the use of the Intel x86-simd-sort and
Google Highway libraries, and may see large (hardware-specific)
speedups,
significant performance improvements for linear algebra
operations on macOS, and wheels that are about 3 times smaller,
numpy.char
fixed-length string operations havebeen accelerated by implementing ufuncs that also support
numpy.dtypes.StringDType
in addition to thefixed-length string dtypes,
numpy.lib.introspect.opt_func_info
, to determinewhich hardware-specific kernels are available and will be
dispatched to.
numpy.save
now uses pickle protocol version 4 for savingarrays with object dtype, which allows for pickle objects larger
than 4GB and improves saving speed by about 5% for large arrays.
structure and each public function now available in a single place.
should make it easier to learn and use NumPy. The number of
objects in the main namespace decreased by ~10% and in
numpy.lib
by ~80%.Canonical dtype names and a new
numpy.isdtype` introspectionfunction,
internals hidden to ease future extensibility,
PyArray_ImportNumPyAPI
and
PyUFunc_ImportUFuncAPI
.This fixes many user surprises about promotions which previously often
depended on data values of input arrays rather than only their dtypes.
Please see the NEP and the numpy-2-migration-guide for details as this
change can lead to changes in output dtypes and lower precision results
for mixed-dtype operations.
int64
rather thanint32
, matching the behavior on other platforms,there is now documentation on NumPy's
module structure,
Furthermore there are many changes to NumPy internals, including
continuing to migrate code from C to C++, that will make it easier to
improve and maintain NumPy in the future.
The "no free lunch" theorem dictates that there is a price to pay for
all these API and behavior improvements and better future extensibility.
This price is:
Backwards compatibility. There are a significant number of breaking
changes to both the Python and C APIs. In the majority of cases,
there are clear error messages that will inform the user how to
adapt their code. However, there are also changes in behavior for
which it was not possible to give such an error message - these
cases are all covered in the Deprecation and Compatibility sections
below, and in the numpy-2-migration-guide.
Note that there is a
ruff
mode to auto-fix many things in Pythoncode.
Breaking changes to the NumPy ABI. As a result, binaries of packages
that use the NumPy C API and were built against a NumPy 1.xx release
will not work with NumPy 2.0. On import, such packages will see an
ImportError
with a message about binary incompatibility.It is possible to build binaries against NumPy 2.0 that will work at
runtime with both NumPy 2.0 and 1.x. See numpy-2-abi-handling for more
details.
All downstream packages that depend on the NumPy ABI are advised
to do a new release built against NumPy 2.0 and verify that that
release works with both 2.0 and 1.26 - ideally in the period between
2.0.0rc1 (which will be ABI-stable) and the final 2.0.0 release to
avoid problems for their users.
The Python versions supported by this release are 3.9-3.12.
NumPy 2.0 Python API removals
np.geterrobj
,np.seterrobj
and the related ufunc keywordargument
extobj=
have been removed. The preferred replacement forall of these is using the context manager
with np.errstate():
.(gh-23922)
np.cast
has been removed. The literal replacement fornp.cast[dtype](arg)
isnp.asarray(arg, dtype=dtype)
.np.source
has been removed. The preferred replacement isinspect.getsource
.np.lookfor
has been removed.(gh-24144)
numpy.who
has been removed. As an alternative for the removedfunctionality, one can use a variable explorer that is available in
IDEs such as Spyder or Jupyter Notebook.
(gh-24321)
Warnings and exceptions present in
numpy.exceptions
,e.g,
numpy.exceptions.ComplexWarning
,numpy.exceptions.VisibleDeprecationWarning
, are nolonger exposed in the main namespace.
Multiple niche enums, expired members and functions have been
removed from the main namespace, such as:
ERR_*
,SHIFT_*
,np.fastCopyAndTranspose
,np.kernel_version
,np.numarray
,np.oldnumeric
andnp.set_numeric_ops
.(gh-24316)
Replaced
from ... import *
in thenumpy/__init__.py
withexplicit imports. As a result, these main namespace members got
removed:
np.FLOATING_POINT_SUPPORT
,np.FPE_*
,np.NINF
,np.PINF
,np.NZERO
,np.PZERO
,np.CLIP
,np.WRAP
,np.WRAP
,np.RAISE
,np.BUFSIZE
,np.UFUNC_BUFSIZE_DEFAULT
,np.UFUNC_PYVALS_NAME
,np.ALLOW_THREADS
,np.MAXDIMS
,np.MAY_SHARE_EXACT
,np.MAY_SHARE_BOUNDS
,add_newdoc
,np.add_docstring
andnp.add_newdoc_ufunc
.(gh-24357)
Alias
np.float_
has been removed. Usenp.float64
instead.Alias
np.complex_
has been removed. Usenp.complex128
instead.Alias
np.longfloat
has been removed. Usenp.longdouble
instead.Alias
np.singlecomplex
has been removed. Usenp.complex64
instead.
Alias
np.cfloat
has been removed. Usenp.complex128
instead.Alias
np.longcomplex
has been removed. Usenp.clongdouble
instead.
Alias
np.clongfloat
has been removed. Usenp.clongdouble
instead.
Alias
np.string_
has been removed. Usenp.bytes_
instead.Alias
np.unicode_
has been removed. Usenp.str_
instead.Alias
np.Inf
has been removed. Usenp.inf
instead.Alias
np.Infinity
has been removed. Usenp.inf
instead.Alias
np.NaN
has been removed. Usenp.nan
instead.Alias
np.infty
has been removed. Usenp.inf
instead.Alias
np.mat
has been removed. Usenp.asmatrix
instead.np.issubclass_
has been removed. Use theissubclass
builtininstead.
np.asfarray
has been removed. Usenp.asarray
with a proper dtypeinstead.
np.set_string_function
has been removed. Usenp.set_printoptions
instead with a formatter for custom printing of NumPy objects.
np.tracemalloc_domain
is now only available fromnp.lib
.np.recfromcsv
andrecfromtxt
are now only available fromnp.lib.npyio
.np.issctype
,np.maximum_sctype
,np.obj2sctype
,np.sctype2char
,np.sctypes
,np.issubsctype
were all removedfrom the main namespace without replacement, as they where niche
members.
Deprecated
np.deprecate
andnp.deprecate_with_doc
has beenremoved from the main namespace. Use
DeprecationWarning
instead.Deprecated
np.safe_eval
has been removed from the main namespace.Use
ast.literal_eval
instead.(gh-24376)
np.find_common_type
has been removed. Usenumpy.promote_types
ornumpy.result_type
instead. To achieve semantics for thescalar_types
argument, usenumpy.result_type
and pass0
,0.0
, or0j
as a Python scalar instead.np.round_
has been removed. Usenp.round
instead.np.nbytes
has been removed. Usenp.dtype(<dtype>).itemsize
instead.
(gh-24477)
np.compare_chararrays
has been removed from the main namespace.Use
np.char.compare_chararrays
instead.The
charrarray
in the main namespace has been deprecated. It canbe imported without a deprecation warning from
np.char.chararray
for now, but we are planning to fully deprecate and remove
chararray
in the future.np.format_parser
has been removed from the main namespace. Usenp.rec.format_parser
instead.(gh-24587)
Support for seven data type string aliases has been removed from
np.dtype
:int0
,uint0
,void0
,object0
,str0
,bytes0
and
bool8
.(gh-24807)
The experimental
numpy.array_api
submodule has been removed. Usethe main
numpy
namespace for regular usage instead, or theseparate
array-api-strict
package for the compliance testing usecase for which
numpy.array_api
was mostly used.(gh-25911)
__array_prepare__
is removedUFuncs called
__array_prepare__
before running computations for normalufunc calls (not generalized ufuncs, reductions, etc.). The function was
also called instead of
__array_wrap__
on the results of some linearalgebra functions.
It is now removed. If you use it, migrate to
__array_ufunc__
or relyon
__array_wrap__
which is called with a context in all cases,although only after the result array is filled. In those code paths,
__array_wrap__
will now be passed a base class, rather than a subclassarray.
(gh-25105)
Deprecations
np.compat
has been deprecated, as Python 2 is no longer supported.numpy.int8
and similar classes will no longer support conversionof out of bounds python integers to integer arrays. For example,
conversion of 255 to int8 will not return -1.
numpy.iinfo(dtype)
can be used to check the machine limits for data types. For example,
np.iinfo(np.uint16)
returns min = 0 and max = 65535.np.array(value).astype(dtype)
will give the desired result.np.safe_eval
has been deprecated.ast.literal_eval
should beused instead.
(gh-23830)
np.recfromcsv
,np.recfromtxt
,np.disp
,np.get_array_wrap
,np.maximum_sctype
,np.deprecate
andnp.deprecate_with_doc
havebeen deprecated.
(gh-24154)
np.trapz
has been deprecated. Usenp.trapezoid
or ascipy.integrate
function instead.np.in1d
has been deprecated. Usenp.isin
instead.Alias
np.row_stack
has been deprecated. Usenp.vstack
directly.(gh-24445)
__array_wrap__
is now passedarr, context, return_scalar
andsupport for implementations not accepting all three are deprecated.
Its signature should be
__array_wrap__(self, arr, context=None, return_scalar=False)
(gh-25409)
Arrays of 2-dimensional vectors for
np.cross
have been deprecated.Use arrays of 3-dimensional vectors instead.
(gh-24818)
np.dtype("a")
alias fornp.dtype(np.bytes_)
was deprecated. Usenp.dtype("S")
alias instead.(gh-24854)
Use of keyword arguments
x
andy
with functionsassert_array_equal
andassert_array_almost_equal
has beendeprecated. Pass the first two arguments as positional arguments
instead.
(gh-24978)
numpy.fft
deprecations for n-D transforms with None values in argumentsUsing
fftn
,ifftn
,rfftn
,irfftn
,fft2
,ifft2
,rfft2
orirfft2
with thes
parameter set to a value that is notNone
andthe
axes
parameter set toNone
has been deprecated, in line with thearray API standard. To retain current behaviour, pass a sequence [0,
..., k-1] to
axes
for an array of dimension k.Furthermore, passing an array to
s
which containsNone
values isdeprecated as the parameter is documented to accept a sequence of
integers in both the NumPy docs and the array API specification. To use
the default behaviour of the corresponding 1-D transform, pass the value
matching the default for its
n
parameter. To use the default behaviourfor every axis, the
s
argument can be omitted.(gh-25495)
np.linalg.lstsq
now defaults to a newrcond
valuenumpy.linalg.lstsq
now uses the new rcond value of themachine precision times
max(M, N)
. Previously, the machine precisionwas used but a FutureWarning was given to notify that this change will
happen eventually. That old behavior can still be achieved by passing
rcond=-1
.(gh-25721)
Expired deprecations
The
np.core.umath_tests
submodule has been removed from the publicAPI. (Deprecated in NumPy 1.15)
(gh-23809)
The
PyDataMem_SetEventHook
deprecation has expired and it isremoved. Use
tracemalloc
and thenp.lib.tracemalloc_domain
domain. (Deprecated in NumPy 1.23)
(gh-23921)
The deprecation of
set_numeric_ops
and the C functionsPyArray_SetNumericOps
andPyArray_GetNumericOps
has been expiredand the functions removed. (Deprecated in NumPy 1.16)
(gh-23998)
The
fasttake
,fastclip
, andfastputmask
ArrFuncs
deprecationis now finalized.
The deprecated function
fastCopyAndTranspose
and its C counterpartare now removed.
The deprecation of
PyArray_ScalarFromObject
is now finalized.(gh-24312)
np.msort
has been removed. For a replacement,np.sort(a, axis=0)
should be used instead.
(gh-24494)
np.dtype(("f8", 1)
will now return a shape 1 subarray dtype ratherthan a non-subarray one.
(gh-25761)
Assigning to the
.data
attribute of an ndarray is disallowed andwill raise.
np.binary_repr(a, width)
will raise if width is too small.Using
NPY_CHAR
inPyArray_DescrFromType()
will raise, useNPY_STRING
NPY_UNICODE
, orNPY_VSTRING
instead.(gh-25794)
Compatibility notes
loadtxt
andgenfromtxt
default encoding changedloadtxt
andgenfromtxt
now both default toencoding=None
which maymainly modify how
converters
work. These will now be passedstr
rather than
bytes
. Pass the encoding explicitly to always get the newor old behavior. For
genfromtxt
the change also means that returnedvalues will now be unicode strings rather than bytes.
(gh-25158)
f2py
compatibility notesf2py
will no longer accept ambiguous-m
and.pyf
CLIcombinations. When more than one
.pyf
file is passed, an error israised. When both
-m
and a.pyf
is passed, a warning is emittedand the
-m
provided name is ignored.(gh-25181)
The
f2py.compile()
helper has been removed because it leakedmemory, has been marked as experimental for several years now, and
was implemented as a thin
subprocess.run
wrapper. It was also oneof the test bottlenecks. See
gh-25122 for the full
rationale. It also used several
np.distutils
features which aretoo fragile to be ported to work with
meson
.Users are urged to replace calls to
f2py.compile
with calls tosubprocess.run("python", "-m", "numpy.f2py",...
instead, and touse environment variables to interact with
meson
. Nativefiles are also an
option.
(gh-25193)
Minor changes in behavior of sorting functions
Due to algorithmic changes and use of SIMD code, sorting functions with
methods that aren't stable may return slightly different results in
2.0.0 compared to 1.26.x. This includes the default method of
numpy.argsort
andnumpy.argpartition
.Removed ambiguity when broadcasting in
np.solve
The broadcasting rules for
np.solve(a, b)
were ambiguous whenb
had1 fewer dimensions than
a
. This has been resolved in abackward-incompatible way and is now compliant with the Array API. The
old behaviour can be reconstructed by using
np.solve(a, b[..., None])[..., 0]
.(gh-25914)
Modified representation for
Polynomial
The representation method for
numpy.polynomial.polynomial.Polynomial
was updated toinclude the domain in the representation. The plain text and latex
representations are now consistent. For example the output of
str(np.polynomial.Polynomial([1, 1], domain=[.1, .2]))
used to be1.0 + 1.0 x
, but now is1.0 + 1.0 (-3.0000000000000004 + 20.0 x)
.(gh-21760)
C API changes
The
PyArray_CGT
,PyArray_CLT
,PyArray_CGE
,PyArray_CLE
,PyArray_CEQ
,PyArray_CNE
macros have been removed.PyArray_MIN
andPyArray_MAX
have been moved fromndarraytypes.h
tonpy_math.h
.(gh-24258)
A C API for working with
numpy.dtypes.StringDType
arrays has been exposed. This includes functions for acquiring and
releasing mutexes which lock access to the string data, as well as
packing and unpacking UTF-8 bytestreams from array entries.
NPY_NTYPES
has been renamed toNPY_NTYPES_LEGACY
as it does notinclude new NumPy built-in DTypes. In particular the new string
DType will likely not work correctly with code that handles legacy
DTypes.
(gh-25347)
The C-API now only exports the static inline function versions of
the array accessors (previously this depended on using "deprecated
API"). While we discourage it, the struct fields can still be used
directly.
(gh-25789)
NumPy now defines
PyArray_Pack
to set an individual memory address.Unlike
PyArray_SETITEM
this function is equivalent to setting anindividual array item and does not require a NumPy array input.
(gh-25954)
The
->f
slot has been removed fromPyArray_Descr
. If you use this slot,replace accessing it with
PyDataType_GetArrFuncs
(see its documentationand the
numpy-2-migration-guide
). In some cases using other functionslike
PyArray_GETITEM
may be an alternatives.PyArray_GETITEM
andPyArray_SETITEM
now require the import ofthe NumPy API table to be used and are no longer defined in
ndarraytypes.h
.(gh-25812)
Due to runtime dependencies, the definition for functionality
accessing the dtype flags was moved from
numpy/ndarraytypes.h
andis only available after including
numpy/ndarrayobject.h
as itrequires
import_array()
. This includesPyDataType_FLAGCHK
,PyDataType_REFCHK
andNPY_BEGIN_THREADS_DESCR
.The dtype flags on
PyArray_Descr
must now be accessed through thePyDataType_FLAGS
inline function to be compatible with both 1.xand 2.x. This function is defined in
npy_2_compat.h
to allowbackporting. Most or all users should use
PyDataType_FLAGCHK
whichis available on 1.x and does not require backporting. Cython users
should use Cython 3. Otherwise access will go through Python unless
they use
PyDataType_FLAGCHK
instead.(gh-25816)
Datetime functionality exposed in the C API and Cython bindings
The functions
NpyDatetime_ConvertDatetime64ToDatetimeStruct
,NpyDatetime_ConvertDatetimeStructToDatetime64
,NpyDatetime_ConvertPyDateTimeToDatetimeStruct
,NpyDatetime_GetDatetimeISO8601StrLen
,NpyDatetime_MakeISO8601Datetime
, andNpyDatetime_ParseISO8601Datetime
have been added to the C API tofacilitate converting between strings, Python datetimes, and NumPy
datetimes in external libraries.
(gh-21199)
Const correctness for the generalized ufunc C API
The NumPy C API's functions for constructing generalized ufuncs
(
PyUFunc_FromFuncAndData
,PyUFunc_FromFuncAndDataAndSignature
,PyUFunc_FromFuncAndDataAndSignatureAndIdentity
) taketypes
anddata
arguments that are not modified by NumPy's internals. Like thename
anddoc
arguments, third-party Python extension modules arelikely to supply these arguments from static constants. The
types
anddata
arguments are now const-correct: they are declared asconst char *types
andvoid *const *data
, respectively. C code shouldnot be affected, but C++ code may be.
(gh-23847)
Larger
NPY_MAXDIMS
andNPY_MAXARGS
,NPY_RAVEL_AXIS
introducedNPY_MAXDIMS
is now 64, you may want to review its use. This is usuallyused in a stack allocation, where the increase should be safe. However,
we do encourage generally to remove any use of
NPY_MAXDIMS
andNPY_MAXARGS
to eventually allow removing the constraint completely.For the conversion helper and C-API functions mirroring Python ones such as
take
,NPY_MAXDIMS
was used to meanaxis=None
. Such usage must be replacedwith
NPY_RAVEL_AXIS
. See alsomigration_maxdims
.(gh-25149)
NPY_MAXARGS
not constant andPyArrayMultiIterObject
size changeSince
NPY_MAXARGS
was increased, it is now a runtime constant and notcompile-time constant anymore. We expect almost no users to notice this.
But if used for stack allocations it now must be replaced with a custom
constant using
NPY_MAXARGS
as an additional runtime check.The
sizeof(PyArrayMultiIterObject)
no longer includes the full size ofthe object. We expect nobody to notice this change. It was necessary to
avoid issues with Cython.
(gh-25271)
Required changes for custom legacy user dtypes
In order to improve our DTypes it is unfortunately necessary to break
the ABI, which requires some changes for dtypes registered with
PyArray_RegisterDataType
. Please see the documentation ofPyArray_RegisterDataType
for how to adapt your code and achievecompatibility with both 1.x and 2.x.
(gh-25792)
New Public DType API
The C implementation of the NEP 42 DType API is now public. While the
DType API has shipped in NumPy for a few versions, it was only usable in
sessions with a special environment variable set. It is now possible to
write custom DTypes outside of NumPy using the new DType API and the
normal
import_array()
mechanism for importing the numpy C API.See
dtype-api
for more details about the API. As always with a new feature,please report any bugs you run into implementing or using a new DType. It is
likely that downstream C code that works with dtypes will need to be updated to
work correctly with new DTypes.
(gh-25754)
New C-API import functions
We have now added
PyArray_ImportNumPyAPI
andPyUFunc_ImportUFuncAPI
as static inline functions to import the NumPy C-API tables. The new
functions have two advantages over
import_array
andimport_ufunc
:light-weight if not, allowing to add them judiciously (although this
is not preferable in most cases).
a
return
statement.The
PyArray_ImportNumPyAPI()
function is included innpy_2_compat.h
for simpler backporting.
(gh-25866)
Structured dtype information access through functions
The dtype structures fields
c_metadata
,names
,fields
, andsubarray
must now be accessed through new functions following the samenames, such as
PyDataType_NAMES
. Direct access of the fields is notvalid as they do not exist for all
PyArray_Descr
instances. Themetadata
field is kept, but the macro version should also bepreferred.
(gh-25802)
Descriptor
elsize
andalignment
accessUnless compiling only with NumPy 2 support, the
elsize
andaligment
fields must now be accessed via
PyDataType_ELSIZE
,PyDataType_SET_ELSIZE
, andPyDataType_ALIGNMENT
. In cases where thedescriptor is attached to an array, we advise using
PyArray_ITEMSIZE
as it exists on all NumPy versions. Please see
migration_c_descr
for more information.(gh-25943)
NumPy 2.0 C API removals
npy_interrupt.h
and the corresponding macros likeNPY_SIGINT_ON
have been removed. We recommend querying
PyErr_CheckSignals()
orPyOS_InterruptOccurred()
periodically (these do currently requireholding the GIL though).
The
noprefix.h
header has been removed. Replace missing symbolswith their prefixed counterparts (usually an added
NPY_
ornpy_
).(gh-23919)
PyUFunc_GetPyVals
,PyUFunc_handlefperr
, andPyUFunc_checkfperr
have been removed. If needed, a new backwards compatible function to
raise floating point errors could be restored. Reason for removal:
there are no known users and the functions would have made
with np.errstate()
fixes much more difficult).(gh-23922)
The
numpy/old_defines.h
which was part of the API deprecated sinceNumPy 1.7 has been removed. This removes macros of the form
PyArray_CONSTANT
. Thereplace_old_macros.sed
script may be useful to convert them to the
NPY_CONSTANT
version.(gh-24011)
The
legacy_inner_loop_selector
member of the ufunc struct isremoved to simplify improvements to the dispatching system. There
are no known users overriding or directly accessing this member.
(gh-24271)
NPY_INTPLTR
has been removed to avoid confusion (seeintp
redefinition).
(gh-24888)
The advanced indexing
MapIter
and related API has been removed.The (truly) public part of it was not well tested and had only one
known user (Theano). Making it private will simplify improvements to
speed up
ufunc.at
, make advanced indexing more maintainable, andwas important for increasing the maximum number of dimensions of
arrays to 64. Please let us know if this API is important to you so
we can find a solution together.
(gh-25138)
The
NPY_MAX_ELSIZE
macro has been removed, as it only everreflected builtin numeric types and served no internal purpose.
(gh-25149)
PyArray_REFCNT
andNPY_REFCOUNT
are removed. UsePy_REFCNT
instead.
(gh-25156)
PyArrayFlags_Type
andPyArray_NewFlagsObject
as well asPyArrayFlagsObject
are private now. There is no known use-case;use the Python API if needed.
PyArray_MoveInto
,PyArray_CastTo
,PyArray_CastAnyTo
areremoved use
PyArray_CopyInto
and if absolutely neededPyArray_CopyAnyInto
(the latter does a flat copy).PyArray_FillObjectArray
is removed, its only true use was forimplementing
np.empty
. Create a new empty array or usePyArray_FillWithScalar()
(decrefs existing objects).PyArray_CompareUCS4
andPyArray_CompareString
are removed. Usethe standard C string comparison functions.
PyArray_ISPYTHON
is removed as it is misleading, has no knownuse-cases, and is easy to replace.
PyArray_FieldNames
is removed, as it is unclear what it would beuseful for. It also has incorrect semantics in some possible
use-cases.
PyArray_TypestrConvert
is removed, since it seems a misnomer andunlikely to be used by anyone. If you know the size or are limited
to few types, just use it explicitly, otherwise go via Python
strings.
(gh-25292)
PyDataType_GetDatetimeMetaData
is removed, it did not actually doanything since at least NumPy 1.7.
(gh-25802)
PyArray_GetCastFunc
is removed. Note that custom legacy userdtypes can still provide a castfunc as their implementation, but any
access to them is now removed. The reason for this is that NumPy
never used these internally for many years. If you use simple
numeric types, please just use C casts directly. In case you require
an alternative, please let us know so we can create new API such as
PyArray_CastBuffer()
which could use old or new cast functionsdepending on the NumPy version.
(gh-25161)
New Features
np.add
was extended to work withunicode
andbytes
dtypes.A new
bitwise_count
functionThis new function counts the number of 1-bits in a number.
numpy.bitwise_count
works on all the numpy integer typesand integer-like objects.
(gh-19355)
macOS Accelerate support, including the ILP64
Support for the updated Accelerate BLAS/LAPACK library, including ILP64
(64-bit integer) support, in macOS 13.3 has been added. This brings
arm64 support, and significant performance improvements of up to 10x for
commonly used linear algebra operations. When Accelerate is selected at
build time, or if no explicit BLAS library selection is done, the 13.3+
version will automatically be used if available.
(gh-24053)
Binary wheels are also available. On macOS >=14.0, users who install
NumPy from PyPI will get wheels built against Accelerate rather than
OpenBLAS.
(gh-25255)
Option to use weights for quantile and percentile functions
A
weights
keyword is now available fornumpy.quantile
,numpy.percentile
,numpy.nanquantile
andnumpy.nanpercentile
. Onlymethod="inverted_cdf"
supports weights.
(gh-24254)
Improved CPU optimization tracking
A new tracer mechanism is available which enables tracking of the
enabled targets for each optimized function (i.e., that uses
hardware-specific SIMD instructions) in the NumPy library. With this
enhancement, it becomes possible to precisely monitor the enabled CPU
dispatch targets for the dispatched functions.
A new function named
opt_func_info
has been added to the new namespacenumpy.lib.introspect
, offering this tracing capability. This function allowsyou to retrieve information about the enabled targets based on function names
and data type signatures.
(gh-24420)
A new Meson backend for
f2py
f2py
in compile mode (i.e.f2py -c
) now accepts the--backend meson
option. This is the default option for Python >=3.12.For older Python versions,
f2py
will still default to--backend distutils
.To support this in realistic use-cases, in compile mode
f2py
takes a--dep
flag one or many times which maps todependency()
calls in themeson
backend, and does nothing in thedistutils
backend.There are no changes for users of
f2py
only as a code generator, i.e.without
-c
.(gh-24532)
bind(c)
support forf2py
Both functions and subroutines can be annotated with
bind(c)
.f2py
will handle both the correct type mapping, and preserve the unique label
for other C interfaces.
Note:
bind(c, name = 'routine_name_other_than_fortran_routine')
isnot honored by the
f2py
bindings by design, sincebind(c)
with thename
is meant to guarantee only the same name in C and Fortran, not inPython and Fortran.
(gh-24555)
A new
strict
option for several testing functionsThe
strict
keyword is now available fornumpy.testing.assert_allclose
,numpy.testing.assert_equal
, andnumpy.testing.assert_array_less
. Settingstrict=True
will disable the broadcasting behaviour for scalars and ensurethat input arrays have the same data type.
(gh-24680,
gh-24770,
gh-24775)
Add
np.core.umath.find
andnp.core.umath.rfind
UFuncsAdd two
find
andrfind
UFuncs that operate on unicode or bytestrings and are used in
np.char
. They operate similar tostr.find
and
str.rfind
.(gh-24868)
diagonal
andtrace
fornumpy.linalg
numpy.linalg.diagonal
andnumpy.linalg.trace
have been added, which arearray API standard-compatible variants of
numpy.diagonal
andnumpy.trace
.They differ in the default axis selection which define 2-D sub-arrays.
(gh-24887)
New
long
andulong
dtypesnumpy.long
andnumpy.ulong
have been added as NumPy integers mapping toC's
long
andunsigned long
. Prior to NumPy 1.24,numpy.long
was an aliasto Python's
int
.(gh-24922)
svdvals
fornumpy.linalg
numpy.linalg.svdvals
has been added. It computes singular values for (a stackof) matrices. Executing
np.svdvals(x)
is the same as callingnp.svd(x, compute_uv=False, hermitian=False)
. This function is compatible with the arrayAPI standard.
(gh-24940)
A new
isdtype
functionnumpy.isdtype
was added to provide a canonical way to classify NumPy'sdtypes in compliance with the array API standard.
(gh-25054)
A new
astype
functionnumpy.astype
was added to provide an array API standard-compatiblealternative to the
numpy.ndarray.astype
method.(gh-25079)
Array API compatible functions' aliases
13 aliases for existing functions were added to improve compatibility
with the array API standard:
acos
,acosh
,asin
,asinh
,atan
,atanh
,atan2
.bitwise_left_shift
,bitwise_invert
,bitwise_right_shift
.concat
,permute_dims
,pow
.numpy.linalg
:tensordot
,matmul
.(gh-25086)
New
unique_*
functionsThe
numpy.unique_all
,numpy.unique_counts
,numpy.unique_inverse
, andnumpy.unique_values
functions have been added. They provide functionality ofnumpy.unique
with different sets of flags. They are array APIstandard-compatible, and because the number of arrays they return does not
depend on the values of input arguments, they are easier to target for JIT
compilation.
(gh-25088)
Matrix transpose support for ndarrays
NumPy now offers support for calculating the matrix transpose of an
array (or stack of arrays). The matrix transpose is equivalent to
swapping the last two axes of an array. Both
np.ndarray
andnp.ma.MaskedArray
now expose a.mT
attribute, and there is amatching new
numpy.matrix_transpose
function.(gh-23762)
Array API compatible functions for
numpy.linalg
Six new functions and two aliases were added to improve compatibility
with the Array API standard for `numpy.linalg`:
numpy.linalg.matrix_norm
- Computes the matrix norm ofa matrix (or a stack of matrices).
numpy.linalg.vector_norm
- Computes the vector norm ofa vector (or batch of vectors).
numpy.vecdot
- Computes the (vector) dot product oftwo arrays.
numpy.linalg.vecdot
- An alias fornumpy.vecdot
.numpy.linalg.matrix_transpose
- An alias fornumpy.matrix_transpose
.(gh-25155)
numpy.linalg.outer
has been added. It computes theouter product of two vectors. It differs from
numpy.outer
by accepting one-dimensional arrays only.This function is compatible with the array API standard.
(gh-25101)
numpy.linalg.cross
has been added. It computes thecross product of two (arrays of) 3-dimensional vectors. It differs
from
numpy.cross
by accepting three-dimensionalvectors only. This function is compatible with the array API
standard.
(gh-25145)
A
correction
argument forvar
andstd
A
correction
argument was added tonumpy.var
andnumpy.std
, which is anarray API standard compatible alternative to
ddof
. As both arguments serve asimilar purpose, only one of them can be provided at the same time.
(gh-25169)
ndarray.device
andndarray.to_device
An
ndarray.device
attribute andndarray.to_device
method were addedto
numpy.ndarray
for array API standard compatibility.Additionally,
device
keyword-only arguments were added to:numpy.asarray
,numpy.arange
,numpy.empty
,numpy.empty_like
,numpy.eye
,numpy.full
,numpy.full_like
,numpy.linspace
,numpy.ones
,numpy.ones_like
,numpy.zeros
, andnumpy.zeros_like
.For all these new arguments, only
device="cpu"
is supported.(gh-25233)
StringDType has been added to NumPy
We have added a new variable-width UTF-8 encoded string data type, implementing
a "NumPy array of Python strings", including support for a user-provided
missing data sentinel. It is intended as a drop-in replacement for arrays of
Python strings and missing data sentinels using the object dtype. See
NEP 55 and the documentation
of stringdtype for more details.
(gh-25347)
New keywords for
cholesky
andpinv
The
upper
andrtol
keywords were added tonumpy.linalg.cholesky
andnumpy.linalg.pinv
,respectively, to improve array API standard compatibility.
For
numpy.linalg.pinv
, if neitherrcond
norrtol
isspecified, the
rcond
's default is used. We plan to deprecate andremove
rcond
in the future.(gh-25388)
New keywords for
sort
,argsort
andlinalg.matrix_rank
New keyword parameters were added to improve array API standard
compatibility:
rtol
was added tonumpy.linalg.matrix_rank
.stable
was added tonumpy.sort
andnumpy.argsort
.(gh-25437)
New
numpy.strings
namespace for string ufuncsNumPy now implements some string operations as ufuncs. The old
np.char
namespace is still available, and where possible the string manipulation
functions in that namespace have been updated to use the new ufuncs,
substantially improving their performance.
Where possible, we suggest updating code to use functions in
np.strings
instead ofnp.char
. In the future we may deprecatenp.char
in favor ofnp.strings
.(gh-25463)
numpy.fft
support for different precisions and in-place calculationsThe various FFT routines in
numpy.fft
now do theircalculations natively in float, double, or long double precision,
depending on the input precision, instead of always calculating in
double precision. Hence, the calculation will now be less precise for
single and more precise for long double precision. The data type of the
output array will now be adjusted accordingly.
Furthermore, all FFT routines have gained an
out
argument that can beused for in-place calculations.
(gh-25536)
configtool and pkg-config support
A new
numpy-config
CLI script is available that can be queried for theNumPy version and for compile flags needed to use the NumPy C API. This
will allow build systems to better support the use of NumPy as a
dependency. Also, a
numpy.pc
pkg-config file is now included withNumpy. In order to find its location for use with
PKG_CONFIG_PATH
, usenumpy-config --pkgconfigdir
.(gh-25730)
Array API standard support in the main namespace
The main
numpy
namespace now supports the array API standard. Seearray-api-standard-compatibility
fordetails.
(gh-25911)
Improvements
Strings are now supported by
any
,all
, and the logical ufuncs.Integer sequences as the shape argument for
memmap
numpy.memmap
can now be created with any integer sequenceas the
shape
argument, such as a list or numpy array of integers.Previously, only the types of tuple and int could be used without
raising an error.
(gh-23729)
errstate
is now faster and context safeThe
numpy.errstate
context manager/decorator is now fasterand safer. Previously, it was not context safe and had (rare) issues
with thread-safety.
(gh-23936)
AArch64 quicksort speed improved by using Highway's VQSort
The first introduction of the Google Highway library, using VQSort on
AArch64. Execution time is improved by up to 16x in some cases, see the
PR for benchmark results. Extensions to other platforms will be done in
the future.
(gh-24018)
Complex types - underlying C type changes
The underlying C types for all of NumPy's complex types have been
changed to use C99 complex types.
While this change does not affect the memory layout of complex
types, it changes the API to be used to directly retrieve or write
the real or complex part of the complex number, since direct field
access (as in
c.real
orc.imag
) is no longer an option. You cannow use utilities provided in
numpy/npy_math.h
to do theseoperations, like this:
To ease cross-version compatibility, equivalent macros and a
compatibility layer have been added which can be used by downstream
packages to continue to support both NumPy 1.x and 2.x. See
complex-numbers
for more info.numpy/npy_common.h
now includescomplex.h
, which means thatcomplex
is now a reserved keyword.(gh-24085)
iso_c_binding
support and improved common blocks forf2py
Previously, users would have to define their own custom
f2cmap
file touse type mappings defined by the Fortran2003
iso_c_binding
intrinsicmodule. These type maps are now natively supported by
f2py
(gh-24555)
f2py
now handlescommon
blocks which havekind
specifications frommodules. This further expands the usability of intrinsics like
iso_fortran_env
andiso_c_binding
.(gh-25186)
Call
str
automatically on third argument to functions likeassert_equal
The third argument to functions like
numpy.testing.assert_equal
now hasstr
called on itautomatically. This way it mimics the built-in
assert
statement, whereassert_equal(a, b, obj)
works likeassert a == b, obj
.(gh-24877)
Support for array-like
atol
/rtol
inisclose
,allclose
The keywords
atol
andrtol
innumpy.isclose
andnumpy.allclose
now accept both scalars and arrays. Anarray, if given, must broadcast to the shapes of the first two array
arguments.
(gh-24878)
Consistent failure messages in test functions
Previously, some
numpy.testing
assertions printed messagesthat referred to the actual and desired results as
x
andy
. Now,these values are consistently referred to as
ACTUAL
andDESIRED
.(gh-24931)
n-D FFT transforms allow
s[i] == -1
The
numpy.fft.fftn
,numpy.fft.ifftn
,numpy.fft.rfftn
,numpy.fft.irfftn
,numpy.fft.fft2
,numpy.fft.ifft2
,numpy.fft.rfft2
andnumpy.fft.irfft2
functions now use the whole input array along the axis
i
ifs[i] == -1
, in line with the array API standard.(gh-25495)
Guard PyArrayScalar_VAL and PyUnicodeScalarObject for the limited API
PyUnicodeScalarObject
holds aPyUnicodeObject
, which is notavailable when using
Py_LIMITED_API
. Add guards to hide it andconsequently also make the
PyArrayScalar_VAL
macro hidden.(gh-25531)
Changes
np.gradient()
now returns a tuple rather than a list making thereturn value immutable.
(gh-23861)
Being fully context and thread-safe,
np.errstate
can only beentered once now.
np.setbufsize
is now tied tonp.errstate()
: leaving annp.errstate
context will also reset thebufsize
.(gh-23936)
A new public
np.lib.array_utils
submodule has been introduced andit currently contains three functions:
byte_bounds
(moved fromnp.lib.utils
),normalize_axis_tuple
andnormalize_axis_index
.(gh-24540)
Introduce
numpy.bool
as the new canonical name forNumPy's boolean dtype, and make
numpy.bool\_
an aliasto it. Note that until NumPy 1.24,
np.bool
was an alias toPython's builtin
bool
. The new name helps with array API standardcompatibility and is a more intuitive name.
(gh-25080)
The
dtype.flags
value was previously stored as a signed integer.This means that the aligned dtype struct flag lead to negative flags
being set (-128 rather than 128). This flag is now stored unsigned
(positive). Code which checks flags manually may need to adapt. This
may include code compiled with Cython 0.29.x.
(gh-25816)
Representation of NumPy scalars changed
As per NEP 51, the scalar representation has been updated to include the type
information to avoid confusion with Python scalars.
Scalars are now printed as
np.float64(3.0)
rather than just3.0
.This may disrupt workflows that store representations of numbers (e.g.,
to files) making it harder to read them. They should be stored as
explicit strings, for example by using
str()
orf"{scalar!s}"
. Forthe time being, affected users can use
np.set_printoptions(legacy="1.25")
to get the old behavior (withpossibly a few exceptions). Documentation of downstream projects may
require larger updates, if code snippets are tested. We are working on
tooling for
doctest-plus
to facilitate updates.
(gh-22449)
Truthiness of NumPy strings changed
NumPy strings previously were inconsistent about how they defined if the
string is
True
orFalse
and the definition did not match the oneused by Python. Strings are now considered
True
when they arenon-empty and
False
when they are empty. This changes the followingdistinct cases:
string_array.astype(np.int64).astype(bool)
, meaning that onlyvalid integers could be cast. Now a string of
"0"
will beconsidered
True
since it is not empty. If you need the oldbehavior, you may use the above step (casting to integer first) or
string_array == "0"
(if the input is only ever0
or1
). To getthe new result on old NumPy versions use
string_array != ""
.np.nonzero(string_array)
previously ignored whitespace so that astring only containing whitespace was considered
False
. Whitespaceis now considered
True
.This change does not affect
np.loadtxt
,np.fromstring
, ornp.genfromtxt
. The first two still use the integer definition, whilegenfromtxt
continues to match for"true"
(ignoring case). However,if
np.bool_
is used as a converter the result will change.The change does affect
np.fromregex
as it uses direct assignments.(gh-23871)
A
mean
keyword was added to var and std functionOften when the standard deviation is needed the mean is also needed. The
same holds for the variance and the mean. Until now the mean is then
calculated twice, the change introduced here for the
numpy.var
andnumpy.std
functions allows for passing in a precalculated mean as an keywordargument. See the docstrings for details and an example illustrating the
speed-up.
(gh-24126)
Remove datetime64 deprecation warning when constructing with timezone
The
numpy.datetime64
method now issues a UserWarning rather than aDeprecationWarning whenever a timezone is included in the datetime string that
is provided.
(gh-24193)
Default integer dtype is now 64-bit on 64-bit Windows
The default NumPy integer is now 64-bit on all 64-bit systems as the
historic 32-bit default on Windows was a common source of issues. Most
users should not notice this. The main issues may occur with code
interfacing with libraries written in a compiled language like C. For
more information see
migration_windows_int64
.(gh-24224)
Renamed
numpy.core
tonumpy._core
Accessing
numpy.core
now emits a DeprecationWarning. In practice wehave found that most downstream usage of
numpy.core
was to accessfunctionality that is available in the main
numpy
namespace. If forsome reason you are using functionality in
numpy.core
that is notavailable in the main
numpy
namespace, this means you are likely usingprivate NumPy internals. You can still access these internals via
numpy._core
without a deprecation warning but we do not provide anybackward compatibility guarantees for NumPy internals. Please open an
issue if you think a mistake was made and something needs to be made
public.
(gh-24634)
The "relaxed strides" debug build option, which was previously enabled
through the
NPY_RELAXED_STRIDES_DEBUG
environment variable or the-Drelaxed-strides-debug
config-settings flag has been removed.(gh-24717)
Redefinition of
np.intp
/np.uintp
(almost never a change)Due to the actual use of these types almost always matching the use of
size_t
/Py_ssize_t
this is now the definition in C. Previously, itmatched
intptr_t
anduintptr_t
which would often have been subtlyincorrect. This has no effect on the vast majority of machines since the
size of these types only differ on extremely niche platforms.
However, it means that:
intp
typed array anymore.The
p
andP
character codes can still be used, however.intptr_t
oruintptr_t
typed arrays in C remainspossible in a cross-platform way via
PyArray_DescrFromType('p')
.nN
were introduced.npy_intp
typed arguments.(gh-24888)
numpy.fft.helper
made privatenumpy.fft.helper
was renamed tonumpy.fft._helper
to indicate thatit is a private submodule. All public functions exported by it should be
accessed from
numpy.fft
.(gh-24945)
numpy.linalg.linalg
made privatenumpy.linalg.linalg
was renamed tonumpy.linalg._linalg
to indicatethat it is a private submodule. All public functions exported by it
should be accessed from
numpy.linalg
.(gh-24946)
Out-of-bound axis not the same as
axis=None
In some cases
axis=32
or for concatenate any large value was the sameas
axis=None
. Except forconcatenate
this was deprecate. Any out ofbound axis value will now error, make sure to use
axis=None
.(gh-25149)
New
copy
keyword meaning forarray
andasarray
constructorsNow
numpy.array
andnumpy.asarray
supportthree values for
copy
parameter:None
- A copy will only be made if it is necessary.True
- Always make a copy.False
- Never make a copy. If a copy is required aValueError
israised.
The meaning of
False
changed as it now raises an exception if a copyis needed.
(gh-25168)
The
__array__
special method now takes acopy
keyword argument.NumPy will pass
copy
to the__array__
special method in situationswhere it would be set to a non-default value (e.g. in a call to
np.asarray(some_object, copy=False)
). Currently, if an unexpectedkeyword argument error is raised after this, NumPy will print a warning
and re-try without the
copy
keyword argument. Implementations ofobjects implementing the
__array__
protocol should accept acopy
keyword argument with the same meaning as when passed to
numpy.array
ornumpy.asarray
.(gh-25168)
Cleanup of initialization of
numpy.dtype
with strings with commasThe interpretation of strings with commas is changed slightly, in that a
trailing comma will now always create a structured dtype. E.g., where
previously
np.dtype("i")
andnp.dtype("i,")
were treated asidentical, now
np.dtype("i,")
will create a structured dtype, with asingle field. This is analogous to
np.dtype("i,i")
creating astructured dtype with two fields, and makes the behaviour consistent
with that expected of tuples.
At the same time, the use of single number surrounded by parenthesis to
indicate a sub-array shape, like in
np.dtype("(2)i,")
, is deprecated.Instead; one should use
np.dtype("(2,)i")
ornp.dtype("2i")
.Eventually, using a number in parentheses will raise an exception, like
is the case for initializations without a comma, like
np.dtype("(2)i")
.(gh-25434)
Change in how complex sign is calculated
Following the array API standard, the complex sign is now calculated as
z / |z|
(instead of the rather less logical case where the sign of thereal part was taken, unless the real part was zero, in which case the
sign of the imaginary part was returned). Like for real numbers, zero is
returned if
z==0
.(gh-25441)
Return types of functions that returned a list of arrays
Functions that returned a list of ndarrays have been changed to return a
tuple of ndarrays instead. Returning tuples consistently whenever a
sequence of arrays is returned makes it easier for JIT compilers like
Numba, as well as for static type checkers in some cases, to support
these functions. Changed functions are:
numpy.atleast_1d
,numpy.atleast_2d
,numpy.atleast_3d
,numpy.broadcast_arrays
,numpy.meshgrid
,numpy.ogrid
,numpy.histogramdd
.np.unique
return_inverse
shape for multi-dimensional inputsWhen multi-dimensional inputs are passed to
np.unique
withreturn_inverse=True
, theunique_inverse
output is now shaped suchthat the input can be reconstructed directly using
np.take(unique, unique_inverse)
whenaxis=None
, andnp.take_along_axis(unique, unique_inverse, axis=axis)
otherwise.(gh-25553,
gh-25570)
any
andall
return booleans for object arraysThe
any
andall
functions and methods now return booleans also forobject arrays. Previously, they did a reduction which behaved like the
Python
or
andand
operators which evaluates to one of the arguments.You can use
np.logical_or.reduce
andnp.logical_and.reduce
toachieve the previous behavior.
(gh-25712)
np.can_cast
cannot be called on Python int, float, or complexnp.can_cast
cannot be called with Python int, float, or complexinstances anymore. This is because NEP 50 means that the result of
can_cast
must not depend on the value passed in. Unfortunately, forPython scalars whether a cast should be considered
"same_kind"
or"safe"
may depend on the context and value so that this is currentlynot implemented. In some cases, this means you may have to add a
specific path for:
if type(obj) in (int, float, complex): ...
.(gh-26393)
Checksums
MD5
SHA256
v1.26.4
Compare Source
NumPy 1.26.4 Release Notes
NumPy 1.26.4 is a maintenance release that fixes bugs and regressions
discovered after the 1.26.3 release. The Python versions supported by
this release are 3.9-3.12. This is the last planned release in the
1.26.x series.
Contributors
A total of 13 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 19 pull requests were merged for this release.
numpy.array_api
: fixlinalg.cholesky
upper decomp...newaxis
to__all__
innumpy.array_api
__config__.py
Checksums
MD5
SHA256
v1.26.3
Compare Source
NumPy 1.26.3 Release Notes
NumPy 1.26.3 is a maintenance release that fixes bugs and regressions
discovered after the 1.26.2 release. The most notable changes are the
f2py bug fixes. The Python versions supported by this release are
3.9-3.12.
Compatibility
f2py
will no longer accept ambiguous-m
and.pyf
CLI combinations.When more than one
.pyf
file is passed, an error is raised. When both-m
and a.pyf
is passed, a warning is emitted and the-m
providedname is ignored.
Improvements
f2py
now handlescommon
blocks which havekind
specifications frommodules. This further expands the usability of intrinsics like
iso_fortran_env
andiso_c_binding
.Contributors
A total of 18 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 42 pull requests were merged for this release.
__getitem__
innumpy.array_api
newaxis
andlinalg.solve
innumpy.array_api
long
typebase
in cpu_avx512_knf2py
wrappers when modules and subroutines...iso_c_type
mappings more consistentlyf2py
rewrite withmeson
detailsnumpy/f2py/_backends
from main.f2py/*.py
from main.Checksums
MD5
SHA256
v1.26.2
Compare Source
NumPy 1.26.2 Release Notes
NumPy 1.26.2 is a maintenance release that fixes bugs and regressions
discovered after the 1.26.1 release. The 1.26.release series is the last
planned minor release series before NumPy 2.0. The Python versions
supported by this release are 3.9-3.12.
Contributors
A total of 13 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 25 pull requests were merged for this release.
import_array()
noexcept
to shuffle helpersallow-noblas
option to true.np.dtype
to itself doesn't crashChecksums
MD5
SHA256
v1.26.1
Compare Source
NumPy 1.26.1 Release Notes
NumPy 1.26.1 is a maintenance release that fixes bugs and regressions
discovered after the 1.26.0 release. In addition, it adds new
functionality for detecting BLAS and LAPACK when building from source.
Highlights are:
The 1.26.release series is the last planned minor release series before
NumPy 2.0. The Python versions supported by this release are 3.9-3.12.
Build system changes
Improved BLAS/LAPACK detection and control
Auto-detection for a number of BLAS and LAPACK is now implemented for
Meson. By default, the build system will try to detect MKL, Accelerate
(on macOS >=13.3), OpenBLAS, FlexiBLAS, BLIS and reference BLAS/LAPACK.
Support for MKL was significantly improved, and support for FlexiBLAS
was added.
New command-line flags are available to further control the selection of
the BLAS and LAPACK libraries to build against.
To select a specific library, use the config-settings interface via
pip
orpypa/build
. E.g., to selectlibblas
/liblapack
, use:This works not only for the libraries named above, but for any library
that Meson is able to detect with the given name through
pkg-config
orCMake.
Besides
-Dblas
and-Dlapack
, a number of other new flags areavailable to control BLAS/LAPACK selection and behavior:
-Dblas-order
and-Dlapack-order
: a list of library names tosearch for in order, overriding the default search order.
-Duse-ilp64
: if set totrue
, use ILP64 (64-bit integer) BLAS andLAPACK. Note that with this release, ILP64 support has been extended
to include MKL and FlexiBLAS. OpenBLAS and Accelerate were supported
in previous releases.
-Dallow-noblas
: if set totrue
, allow NumPy to build with itsinternal (very slow) fallback routines instead of linking against an
external BLAS/LAPACK library. The default for this flag may be
changed to ``true`` in a future 1.26.x release, however for
1.26.1 we'd prefer to keep it as ``false`` because if failures
to detect an installed library are happening, we'd like a bug
report for that, so we can quickly assess whether the new
auto-detection machinery needs further improvements.
-Dmkl-threading
: to select the threading layer for MKL. There arefour options:
seq
,iomp
,gomp
andtbb
. The default isauto
, which selects from those four as appropriate given theversion of MKL selected.
-Dblas-symbol-suffix
: manually select the symbol suffix to use forthe library - should only be needed for linking against libraries
built in a non-standard way.
New features
numpy._core
submodule stubsnumpy._core
submodule stubs were added to provide compatibility withpickled arrays created using NumPy 2.0 when running Numpy 1.26.
Contributors
A total of 13 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 20 pull requests were merged for this release.
-march=native
...use-compute-credits
for Cirrus.NumpyUnpickler
for backportingnumpy._core
stubs. RemoveNumpyUnpickler
Checksums
MD5
SHA256
v1.26.0
Compare Source
NumPy 1.26.0 Release Notes
The NumPy 1.26.0 release is a continuation of the 1.25.x release cycle
with the addition of Python 3.12.0 support. Python 3.12 dropped
distutils, consequently supporting it required finding a replacement for
the setup.py/distutils based build system NumPy was using. We have
chosen to use the Meson build system instead, and this is the first
NumPy release supporting it. This is also the first release that
supports Cython 3.0 in addition to retaining 0.29.X compatibility.
Supporting those two upgrades was a large project, over 100 files have
been touched in this release. The changelog doesn't capture the full
extent of the work, special thanks to Ralf Gommers, Sayed Adel, Stéfan
van der Walt, and Matti Picus who did much of the work in the main
development branch.
The highlights of this release are:
The Python versions supported in this release are 3.9-3.12.
New Features
Array API v2022.12 support in
numpy.array_api
numpy.array_api
now full supports thev2022.12 version of the array API standard. Note that this does not
yet include the optional
fft
extension in the standard.(gh-23789)
Support for the updated Accelerate BLAS/LAPACK library
Support for the updated Accelerate BLAS/LAPACK library, including ILP64
(64-bit integer) support, in macOS 13.3 has been added. This brings
arm64 support, and significant performance improvements of up to 10x for
commonly used linear algebra operations. When Accelerate is selected at
build time, the 13.3+ version will automatically be used if available.
(gh-24053)
meson
backend forf2py
f2py
in compile mode (i.e.f2py -c
) now accepts the--backend meson
option. This is the default option for Python3.12
on-wards. Older versions will still default to
--backend distutils
.To support this in realistic use-cases, in compile mode
f2py
takes a--dep
flag one or many times which maps todependency()
calls in themeson
backend, and does nothing in thedistutils
backend.There are no changes for users of
f2py
only as a code generator, i.e.without
-c
.(gh-24532)
bind(c)
support forf2py
Both functions and subroutines can be annotated with
bind(c)
.f2py
will handle both the correct type mapping, and preserve the unique label
for other
C
interfaces.Note:
bind(c, name = 'routine_name_other_than_fortran_routine')
isnot honored by the
f2py
bindings by design, sincebind(c)
with thename
is meant to guarantee only the same name inC
andFortran
,not in
Python
andFortran
.(gh-24555)
Improvements
iso_c_binding
support forf2py
Previously, users would have to define their own custom
f2cmap
file touse type mappings defined by the Fortran2003
iso_c_binding
intrinsicmodule. These type maps are now natively supported by
f2py
(gh-24555)
Build system changes
In this release, NumPy has switched to Meson as the build system and
meson-python as the build backend. Installing NumPy or building a wheel
can be done with standard tools like
pip
andpypa/build
. Thefollowing are supported:
pip install numpy
or (in a cloned repo)pip install .
python -m build
(preferred), orpip wheel .
pip install -e . --no-build-isolation
spin:
spin build
.All the regular
pip
andpypa/build
flags (e.g.,--no-build-isolation
) should work as expected.NumPy-specific build customization
Many of the NumPy-specific ways of customizing builds have changed. The
NPY_*
environment variables which control BLAS/LAPACK, SIMD,threading, and other such options are no longer supported, nor is a
site.cfg
file to select BLAS and LAPACK. Instead, there arecommand-line flags that can be passed to the build via
pip
/build
'sconfig-settings interface. These flags are all listed in the
meson_options.txt
file in the root of the repo. Detailed documentedwill be available before the final 1.26.0 release; for now please see
the SciPy "building from source" docs
since most build customization works in an almost identical way in SciPy as it
does in NumPy.
Build dependencies
While the runtime dependencies of NumPy have not changed, the build
dependencies have. Because we temporarily vendor Meson and meson-python,
there are several new dependencies - please see the
[build-system]
section of
pyproject.toml
for details.Troubleshooting
This build system change is quite large. In case of unexpected issues,
it is still possible to use a
setup.py
-based build as a temporaryworkaround (on Python 3.9-3.11, not 3.12), by copying
pyproject.toml.setuppy
topyproject.toml
. However, please open anissue with details on the NumPy issue tracker. We aim to phase out
setup.py
builds as soon as possible, and therefore would like to seeall potential blockers surfaced early on in the 1.26.0 release cycle.
Contributors
A total of 20 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 59 pull requests were merged for this release.
_NestedSequence.__getitem__
signatureextbuild.py
from main.asv dev
has been removed, useasv run
._umath_linalg
dependenciesbinding
directive to "False".casting
keyword tonp.clip
fromnumeric.pyi
iso_c_binding
type maps and fixbind(c)
...binary_repr
to accept any object implementing...dtype
andgeneric
hashabletyping.assert_type
meson
backend forf2py
spin docs
...Checksums
MD5
SHA256
v1.25.2
Compare Source
NumPy 1.25.2 Release Notes
NumPy 1.25.2 is a maintenance release that fixes bugs and regressions
discovered after the 1.25.1 release. This is the last planned release in
the 1.25.x series, the next release will be 1.26.0, which will use the
meson build system and support Python 3.12. The Python versions
supported by this release are 3.9-3.11.
Contributors
A total of 13 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 19 pull requests were merged for this release.
-ftrapping-math
with Clang on macOSnp.__all__
getenv
call used for memory policy warningChecksums
MD5
SHA256
v1.25.1
Compare Source
NumPy 1.25.1 Release Notes
NumPy 1.25.1 is a maintenance release that fixes bugs and regressions
discovered after the 1.25.0 release. The Python versions supported by
this release are 3.9-3.11.
Contributors
A total of 10 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 14 pull requests were merged for this release.
return NULL
to begoto fail
__array_ufunc__
works without any kwargs passedChecksums
MD5
SHA256
v1.25.0
Compare Source
NumPy 1.25.0 Release Notes
The NumPy 1.25.0 release continues the ongoing work to improve the
handling and promotion of dtypes, increase the execution speed, and
clarify the documentation. There has also been work to prepare for the
future NumPy 2.0.0 release, resulting in a large number of new and
expired deprecation. Highlights are:
@=
).We will be releasing a NumPy 1.26 when Python 3.12 comes out. That is
needed because distutils has been dropped by Python 3.12 and we will be
switching to using meson for future builds. The next mainline release
will be NumPy 2.0.0. We plan that the 2.0 series will still support
downstream projects built against earlier versions of NumPy.
The Python versions supported in this release are 3.9-3.11.
Deprecations
np.core.MachAr
is deprecated. It is private API. In names definedin
np.core
should generally be considered private.(gh-22638)
np.finfo(None)
is deprecated.(gh-23011)
np.round_
is deprecated. Usenp.round
instead.(gh-23302)
np.product
is deprecated. Usenp.prod
instead.(gh-23314)
np.cumproduct
is deprecated. Usenp.cumprod
instead.(gh-23314)
np.sometrue
is deprecated. Usenp.any
instead.(gh-23314)
np.alltrue
is deprecated. Usenp.all
instead.(gh-23314)
Only ndim-0 arrays are treated as scalars. NumPy used to treat all
arrays of size 1 (e.g.,
np.array([3.14])
) as scalars. In thefuture, this will be limited to arrays of ndim 0 (e.g.,
np.array(3.14)
). The following expressions will report adeprecation warning:
(gh-10615)
numpy.find_common_type
is now deprecated and its useshould be replaced with either
numpy.result_type
ornumpy.promote_types
. Most users leave the secondscalar_types
argument tofind_common_type
as[]
in which casenp.result_type
andnp.promote_types
are both faster and morerobust. When not using
scalar_types
the main difference is thatthe replacement intentionally converts non-native byte-order to
native byte order. Further,
find_common_type
returnsobject
dtype rather than failing promotion. This leads to differences when
the inputs are not all numeric. Importantly, this also happens for
e.g. timedelta/datetime for which NumPy promotion rules are
currently sometimes surprising.
When the
scalar_types
argument is not[]
things are morecomplicated. In most cases, using
np.result_type
and passing thePython values
0
,0.0
, or0j
has the same result as usingint
,float
, orcomplex
inscalar_types
.When
scalar_types
is constructed,np.result_type
is the correctreplacement and it may be passed scalar values like
np.float32(0.0)
. Passing values other than 0, may lead tovalue-inspecting behavior (which
np.find_common_type
never usedand NEP 50 may change in the future). The main possible change in
behavior in this case, is when the array types are signed integers
and scalar types are unsigned.
If you are unsure about how to replace a use of
scalar_types
orwhen non-numeric dtypes are likely, please do not hesitate to open a
NumPy issue to ask for help.
(gh-22539)
Expired deprecations
np.core.machar
andnp.finfo.machar
have been removed.(gh-22638)
+arr
will now raise an error when the dtype is not numeric (andpositive is undefined).
(gh-22998)
A sequence must now be passed into the stacking family of functions
(
stack
,vstack
,hstack
,dstack
andcolumn_stack
).(gh-23019)
np.clip
now defaults to same-kind casting. Falling back to unsafecasting was deprecated in NumPy 1.17.
(gh-23403)
np.clip
will now propagatenp.nan
values passed asmin
ormax
. Previously, a scalar NaN was usually ignored. This wasdeprecated in NumPy 1.17.
(gh-23403)
The
np.dual
submodule has been removed.(gh-23480)
NumPy now always ignores sequence behavior for an array-like
(defining one of the array protocols). (Deprecation started NumPy
1.20)
(gh-23660)
The niche
FutureWarning
when casting to a subarray dtype inastype
or the array creation functions such asasarray
is nowfinalized. The behavior is now always the same as if the subarray
dtype was wrapped into a single field (which was the workaround,
previously). (FutureWarning since NumPy 1.20)
(gh-23666)
==
and!=
warnings have been finalized. The==
and!=
operators on arrays now always:
raise errors that occur during comparisons such as when the
arrays have incompatible shapes
(
np.array([1, 2]) == np.array([1, 2, 3])
).return an array of all
True
or allFalse
when values arefundamentally not comparable (e.g. have different dtypes). An
example is
np.array(["a"]) == np.array([1])
.This mimics the Python behavior of returning
False
andTrue
when comparing incompatible types like
"a" == 1
and"a" != 1
. For a long time these gaveDeprecationWarning
orFutureWarning
.(gh-22707)
Nose support has been removed. NumPy switched to using pytest in
2018 and nose has been unmaintained for many years. We have kept
NumPy's nose support to avoid breaking downstream projects who
might have been using it and not yet switched to pytest or some
other testing framework. With the arrival of Python 3.12, unpatched
nose will raise an error. It is time to move on.
Decorators removed:
These are not to be confused with pytest versions with similar
names, e.g., pytest.mark.slow, pytest.mark.skipif,
pytest.mark.parametrize.
Functions removed:
(gh-23041)
The
numpy.testing.utils
shim has been removed. Importing from thenumpy.testing.utils
shim has been deprecated since 2019, the shimhas now been removed. All imports should be made directly from
numpy.testing
.(gh-23060)
The environment variable to disable dispatching has been removed.
Support for the
NUMPY_EXPERIMENTAL_ARRAY_FUNCTION
environmentvariable has been removed. This variable disabled dispatching with
__array_function__
.(gh-23376)
Support for
y=
as an alias ofout=
has been removed. Thefix
,isposinf
andisneginf
functions allowed usingy=
as a(deprecated) alias for
out=
. This is no longer supported.(gh-23376)
Compatibility notes
The
busday_count
method now correctly handles cases where thebegindates
is later in time than theenddates
. Previously, theenddates
was included, even though the documentation states it isalways excluded.
(gh-23229)
When comparing datetimes and timedelta using
np.equal
ornp.not_equal
numpy previously allowed the comparison withcasting="unsafe"
. This operation now fails. Forcing the outputdtype using the
dtype
kwarg can make the operation succeed, but wedo not recommend it.
(gh-22707)
When loading data from a file handle using
np.load
, if the handleis at the end of file, as can happen when reading multiple arrays by
calling
np.load
repeatedly, numpy previously raisedValueError
if
allow_pickle=False
, andOSError
ifallow_pickle=True
. Nowit raises
EOFError
instead, in both cases.(gh-23105)
np.pad
withmode=wrap
pads with strict multiples of original dataCode based on earlier version of
pad
that usesmode="wrap"
willreturn different results when the padding size is larger than initial
array.
np.pad
withmode=wrap
now always fills the space with strictmultiples of original data even if the padding size is larger than the
initial array.
(gh-22575)
Cython
long_t
andulong_t
removedlong_t
andulong_t
were aliases forlonglong_t
andulonglong_t
and confusing (a remainder from of Python 2). This change may lead to
the errors:
We recommend use of bit-sized types such as
cnp.int64_t
or the use ofcnp.intp_t
which is 32 bits on 32 bit systems and 64 bits on 64 bitsystems (this is most compatible with indexing). If C
long
is desired,use plain
long
ornpy_long
.cnp.int_t
is alsolong
(NumPy'sdefault integer). However,
long
is 32 bit on 64 bit windows and we maywish to adjust this even in NumPy. (Please do not hesitate to contact
NumPy developers if you are curious about this.)
(gh-22637)
Changed error message and type for bad
axes
argument toufunc
The error message and type when a wrong
axes
value is passed toufunc(..., axes=[...])
has changed. The message is now moreindicative of the problem, and if the value is mismatched an
AxisError
will be raised. ATypeError
will still be raised forinvalidinput types.
(gh-22675)
Array-likes that define
__array_ufunc__
can now override ufuncs if used aswhere
If the
where
keyword argument of anumpy.ufunc
{.interpreted-textrole="class"} is a subclass of
numpy.ndarray
{.interpreted-textrole="class"} or is a duck type that defines
numpy.class.__array_ufunc__
{.interpreted-text role="func"} it canoverride the behavior of the ufunc using the same mechanism as the input
and output arguments. Note that for this to work properly, the
where.__array_ufunc__
implementation will have to unwrap thewhere
argument to pass it into the default implementation of the
ufunc
or,for
numpy.ndarray
{.interpreted-text role="class"} subclasses beforeusing
super().__array_ufunc__
.(gh-23240)
Compiling against the NumPy C API is now backwards compatible by default
NumPy now defaults to exposing a backwards compatible subset of the
C-API. This makes the use of
oldest-supported-numpy
unnecessary.Libraries can override the default minimal version to be compatible with
using:
before including NumPy or by passing the equivalent
-D
option to thecompiler. The NumPy 1.25 default is
NPY_1_19_API_VERSION
. Because theNumPy 1.19 C API was identical to the NumPy 1.16 one resulting programs
will be compatible with NumPy 1.16 (from a C-API perspective). This
default will be increased in future non-bugfix releases. You can still
compile against an older NumPy version and run on a newer one.
For more details please see
for-downstream-package-authors
{.interpreted-text role="ref"}.(gh-23528)
New Features
np.einsum
now accepts arrays withobject
dtypeThe code path will call python operators on object dtype arrays, much
like
np.dot
andnp.matmul
.(gh-18053)
Add support for inplace matrix multiplication
It is now possible to perform inplace matrix multiplication via the
@=
operator.
(gh-21120)
Added
NPY_ENABLE_CPU_FEATURES
environment variableUsers may now choose to enable only a subset of the built CPU features
at runtime by specifying the
NPY_ENABLE_CPU_FEATURES
environment variable. Note that these specified features must be outside
the baseline, since those are always assumed. Errors will be raised if
attempting to enable a feature that is either not supported by your CPU,
or that NumPy was not built with.
(gh-22137)
NumPy now has an
np.exceptions
namespaceNumPy now has a dedicated namespace making most exceptions and warnings
available. All of these remain available in the main namespace, although
some may be moved slowly in the future. The main reason for this is to
increase discoverability and add future exceptions.
(gh-22644)
np.linalg
functions return NamedTuplesnp.linalg
functions that return tuples now return namedtuples. Thesefunctions are
eig()
,eigh()
,qr()
,slogdet()
, andsvd()
. Thereturn type is unchanged in instances where these functions return
non-tuples with certain keyword arguments (like
svd(compute_uv=False)
).(gh-22786)
String functions in
np.char
are compatible with NEP 42 custom dtypesCustom dtypes that represent unicode strings or byte strings can now be
passed to the string functions in
np.char
.(gh-22863)
String dtype instances can be created from the string abstract dtype classes
It is now possible to create a string dtype instance with a size without
using the string name of the dtype. For example,
type(np.dtype('U'))(8)
will create a dtype that is equivalent tonp.dtype('U8')
. This feature is most useful when writing generic codedealing with string dtype classes.
(gh-22963)
Fujitsu C/C++ compiler is now supported
Support for Fujitsu compiler has been added. To build with Fujitsu
compiler, run:
SSL2 is now supported
Support for SSL2 has been added. SSL2 is a library that provides
OpenBLAS compatible GEMM functions. To enable SSL2, it need to edit
site.cfg and build with Fujitsu compiler. See site.cfg.example.
(gh-22982)
Improvements
NDArrayOperatorsMixin
specifies that it has no__slots__
The
NDArrayOperatorsMixin
class now specifies that it contains no__slots__
, ensuring that subclasses can now make use of this featurein Python.
(gh-23113)
Fix power of complex zero
np.power
now returns a different result for0^{non-zero}
for complexnumbers. Note that the value is only defined when the real part of the
exponent is larger than zero. Previously, NaN was returned unless the
imaginary part was strictly zero. The return value is either
0+0j
or0-0j
.(gh-18535)
New
DTypePromotionError
NumPy now has a new
DTypePromotionError
which is used when two dtypescannot be promoted to a common one, for example:
raises this new exception.
(gh-22707)
np.show_config
uses information from MesonBuild and system information now contains information from Meson.
np.show_config
now has a new optional parametermode
tohelp customize the output.
(gh-22769)
Fix
np.ma.diff
not preserving the mask when called with arguments prepend/append.Calling
np.ma.diff
with arguments prepend and/or append now returns aMaskedArray
with the input mask preserved.Previously, a
MaskedArray
without the mask was returned.(gh-22776)
Corrected error handling for NumPy C-API in Cython
Many NumPy C functions defined for use in Cython were lacking the
correct error indicator like
except -1
orexcept *
. These have nowbeen added.
(gh-22997)
Ability to directly spawn random number generators
numpy.random.Generator.spawn
now allows to directly spawn new independentchild generators via the
numpy.random.SeedSequence.spawn
mechanism.numpy.random.BitGenerator.spawn
does the same for the underlying bitgenerator.
Additionally,
numpy.random.BitGenerator.seed_seq
now givesdirect access to the seed sequence used for initializing the bit
generator. This allows for example:
safely use rng, child_rng1, and child_rng2
Previously, this was hard to do without passing the
SeedSequence
explicitly. Please see
numpy.random.SeedSequence
for moreinformation.
(gh-23195)
numpy.logspace
now supports a non-scalarbase
argumentThe
base
argument ofnumpy.logspace
can now be array-like if it isbroadcastable against the
start
andstop
arguments.(gh-23275)
np.ma.dot()
now supports for non-2d arraysPreviously
np.ma.dot()
only worked ifa
andb
were both 2d. Now itworks for non-2d arrays as well as
np.dot()
.(gh-23322)
Explicitly show keys of .npz file in repr
NpzFile
shows keys of loaded .npz file when printed.(gh-23357)
NumPy now exposes DType classes in
np.dtypes
The new
numpy.dtypes
module now exposes DType classes and will containfuture dtype related functionality. Most users should have no need to
use these classes directly.
(gh-23358)
Drop dtype metadata before saving in .npy or .npz files
Currently, a
*.npy
file containing a table with a dtype with metadata cannotbe read back. Now,
np.save
andnp.savez
drop metadata before saving.(gh-23371)
numpy.lib.recfunctions.structured_to_unstructured
returns views in more casesstructured_to_unstructured
now returns a view, if the stride betweenthe fields is constant. Prior, padding between the fields or a reversed
field would lead to a copy. This change only applies to
ndarray
,memmap
andrecarray
. For all other array subclasses, the behaviorremains unchanged.
(gh-23652)
Signed and unsigned integers always compare correctly
When
uint64
andint64
are mixed in NumPy, NumPy typically promotesboth to
float64
. This behavior may be argued about but is confusingfor comparisons
==
,<=
, since the results returned can be incorrectbut the conversion is hidden since the result is a boolean. NumPy will
now return the correct results for these by avoiding the cast to float.
(gh-23713)
Performance improvements and changes
Faster
np.argsort
on AVX-512 enabled processors32-bit and 64-bit quicksort algorithm for np.argsort gain up to 6x speed
up on processors that support AVX-512 instruction set.
Thanks to Intel corporation for sponsoring
this work.
(gh-23707)
Faster
np.sort
on AVX-512 enabled processorsQuicksort for 16-bit and 64-bit dtypes gain up to 15x and 9x speed up on
processors that support AVX-512 instruction set.
Thanks to Intel corporation for sponsoring
this work.
(gh-22315)
__array_function__
machinery is now much fasterThe overhead of the majority of functions in NumPy is now smaller
especially when keyword arguments are used. This change significantly
speeds up many simple function calls.
(gh-23020)
ufunc.at
can be much fasterGeneric
ufunc.at
can be up to 9x faster. The conditions for thisspeedup:
If ufuncs with appropriate indexed loops on 1d arguments with the above
conditions,
ufunc.at
can be up to 60x faster (an additional 7xspeedup). Appropriate indexed loops have been added to
add
,subtract
,multiply
,floor_divide
,maximum
,minimum
,fmax
,and
fmin
.The internal logic is similar to the logic used for regular ufuncs,
which also have fast paths.
Thanks to the D. E. Shaw group for sponsoring
this work.
(gh-23136)
Faster membership test on
NpzFile
Membership test on
NpzFile
will no longer decompress the archive if itis successful.
(gh-23661)
Changes
np.r_[]
andnp.c_[]
with certain scalar valuesIn rare cases, using mainly
np.r_
with scalars can lead to differentresults. The main potential changes are highlighted by the following:
Where the second example returned:
The first one is due to a signed integer scalar with an unsigned integer
array, while the second is due to
255
not fitting intoint8
andNumPy currently inspecting values to make this work. (Note that the
second example is expected to change in the future due to
NEP 50 <NEP50>
{.interpreted-text role="ref"}; it will then raise anerror.)
(gh-22539)
Most NumPy functions are wrapped into a C-callable
To speed up the
__array_function__
dispatching, most NumPy functionsare now wrapped into C-callables and are not proper Python functions or
C methods. They still look and feel the same as before (like a Python
function), and this should only improve performance and user experience
(cleaner tracebacks). However, please inform the NumPy developers if
this change confuses your program for some reason.
(gh-23020)
C++ standard library usage
NumPy builds now depend on the C++ standard library, because the
numpy.core._multiarray_umath
extension is linked with the C++ linker.(gh-23601)
Checksums
MD5
SHA256
v1.24.4
Compare Source
NumPy 1.24.4 Release Notes
NumPy 1.24.4 is a maintenance release that fixes a few bugs
discovered after the 1.24.3 release. It is the last planned
release in the 1.24.x cycle. The Python versions supported by
this release are 3.8-3.11.
Contributors
A total of 4 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 6 pull requests were merged for this release.
metadata
parameter of...Checksums
MD5
SHA256
v1.24.3
Compare Source
NumPy 1.24.3 Release Notes
NumPy 1.24.3 is a maintenance release that fixes bugs and regressions
discovered after the 1.24.2 release. The Python versions supported by
this release are 3.8-3.11.
Contributors
A total of 12 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 17 pull requests were merged for this release.
__init__.pyi
.d
argument to fftfreq and rfftfreq as optional...msort
like=
dispatched functionsorder="A"
ororder="K"
Checksums
MD5
SHA256
v1.24.2
Compare Source
NumPy 1.24.2 Release Notes
NumPy 1.24.2 is a maintenance release that fixes bugs and regressions
discovered after the 1.24.1 release. The Python versions supported by
this release are 3.8-3.11.
Contributors
A total of 14 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 17 pull requests were merged for this release.
_Alignof
rather thanoffsetof()
on most compilersAny
parameter to thenpt.ArrayLike
...Checksums
MD5
SHA256
v1.24.1
Compare Source
NumPy 1.24.1 Release Notes
NumPy 1.24.1 is a maintenance release that fixes bugs and regressions
discovered after the 1.24.0 release. The Python versions supported by
this release are 3.8-3.11.
Contributors
A total of 12 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 18 pull requests were merged for this release.
charset_normalizer
.Checksums
MD5
SHA256
v1.24.0
Compare Source
NumPy 1.24 Release Notes
The NumPy 1.24.0 release continues the ongoing work to improve the
handling and promotion of dtypes, increase the execution speed, and
clarify the documentation. There are also a large number of new and
expired deprecations due to changes in promotion and cleanups. This
might be called a deprecation release. Highlights are
See below for the details,
This release supports Python versions 3.8-3.11.
Deprecations
Deprecate fastCopyAndTranspose and PyArray_CopyAndTranspose
The
numpy.fastCopyAndTranspose
function has been deprecated. Use thecorresponding copy and transpose methods directly:
The underlying C function
PyArray_CopyAndTranspose
has also beendeprecated from the NumPy C-API.
(gh-22313)
Conversion of out-of-bound Python integers
Attempting a conversion from a Python integer to a NumPy value will now
always check whether the result can be represented by NumPy. This means
the following examples will fail in the future and give a
DeprecationWarning
now:Many of these did succeed before. Such code was mainly useful for
unsigned integers with negative values such as
np.uint8(-1)
givingnp.iinfo(np.uint8).max
.Note that conversion between NumPy integers is unaffected, so that
np.array(-1).astype(np.uint8)
continues to work and use C integeroverflow logic. For negative values, it will also work to view the
array:
np.array(-1, dtype=np.int8).view(np.uint8)
. In some cases,using
np.iinfo(np.uint8).max
orval % 2**8
may also work well.In rare cases input data may mix both negative values and very large
unsigned values (i.e.
-1
and2**63
). There it is unfortunatelynecessary to use
%
on the Python value or use signed or unsignedconversion depending on whether negative values are expected.
(gh-22385)
Deprecate
msort
The
numpy.msort
function is deprecated. Usenp.sort(a, axis=0)
instead.
(gh-22456)
np.str0
and similar are now deprecatedThe scalar type aliases ending in a 0 bit size:
np.object0
,np.str0
,np.bytes0
,np.void0
,np.int0
,np.uint0
as well asnp.bool8
arenow deprecated and will eventually be removed.
(gh-22607)
Expired deprecations
The
normed
keyword argument has been removed from[np.histogram]{.title-ref}, [np.histogram2d]{.title-ref}, and
[np.histogramdd]{.title-ref}. Use
density
instead. Ifnormed
waspassed by position,
density
is now used.(gh-21645)
Ragged array creation will now always raise a
ValueError
unlessdtype=object
is passed. This includes very deeply nestedsequences.
(gh-22004)
Support for Visual Studio 2015 and earlier has been removed.
Support for the Windows Interix POSIX interop layer has been
removed.
(gh-22139)
Support for Cygwin < 3.3 has been removed.
(gh-22159)
The mini() method of
np.ma.MaskedArray
has been removed. Useeither
np.ma.MaskedArray.min()
ornp.ma.minimum.reduce()
.The single-argument form of
np.ma.minimum
andnp.ma.maximum
hasbeen removed. Use
np.ma.minimum.reduce()
ornp.ma.maximum.reduce()
instead.(gh-22228)
Passing dtype instances other than the canonical (mainly native
byte-order) ones to
dtype=
orsignature=
in ufuncs will nowraise a
TypeError
. We recommend passing the strings"int8"
orscalar types
np.int8
since the byte-order, datetime/timedeltaunit, etc. are never enforced. (Initially deprecated in NumPy 1.21.)
(gh-22540)
The
dtype=
argument to comparison ufuncs is now applied correctly.That means that only
bool
andobject
are valid values anddtype=object
is enforced.(gh-22541)
The deprecation for the aliases
np.object
,np.bool
,np.float
,np.complex
,np.str
, andnp.int
is expired (introduces NumPy1.20). Some of these will now give a FutureWarning in addition to
raising an error since they will be mapped to the NumPy scalars in
the future.
(gh-22607)
Compatibility notes
array.fill(scalar)
may behave slightly differentnumpy.ndarray.fill
may in some cases behave slightly different now dueto the fact that the logic is aligned with item assignment:
is now identical to:
Previously casting may have produced slightly different answers when
using values that could not be represented in the target
dtype
or whenthe target had
object
dtype.(gh-20924)
Subarray to object cast now copies
Casting a dtype that includes a subarray to an object will now ensure a
copy of the subarray. Previously an unsafe view was returned:
Is now always false. While previously it was true for the specific cast.
(gh-21925)
Returned arrays respect uniqueness of dtype kwarg objects
When the
dtype
keyword argument is used with:py
np.array()
{.interpreted-text role="func"} or:py
asarray()
{.interpreted-text role="func"}, the dtype of the returnedarray now always exactly matches the dtype provided by the caller.
In some cases this change means that a view rather than the input
array is returned. The following is an example for this on 64bit Linux
where
long
andlonglong
are the same precision but differentdtypes
:Before the change, the
dtype
did not match becausenew is arr
wasTrue
.(gh-21995)
DLPack export raises
BufferError
When an array buffer cannot be exported via DLPack a
BufferError
isnow always raised where previously
TypeError
orRuntimeError
wasraised. This allows falling back to the buffer protocol or
__array_interface__
when DLPack was tried first.(gh-22542)
NumPy builds are no longer tested on GCC-6
Ubuntu 18.04 is deprecated for GitHub actions and GCC-6 is not available
on Ubuntu 20.04, so builds using that compiler are no longer tested. We
still test builds using GCC-7 and GCC-8.
(gh-22598)
New Features
New attribute
symbol
added to polynomial classesThe polynomial classes in the
numpy.polynomial
package have a newsymbol
attribute which is used to represent the indeterminate of thepolynomial. This can be used to change the value of the variable when
printing:
Note that the polynomial classes only support 1D polynomials, so
operations that involve polynomials with different symbols are
disallowed when the result would be multivariate:
The symbol can be any valid Python identifier. The default is
symbol=x
, consistent with existing behavior.(gh-16154)
F2PY support for Fortran
character
stringsF2PY now supports wrapping Fortran functions with:
character x
)character, dimension(n) :: x
)character(len=10) x
)character(len=10), dimension(n, m) :: x
)arguments, including passing Python unicode strings as Fortran character
string arguments.
(gh-19388)
New function
np.show_runtime
A new function
numpy.show_runtime
has been added to display theruntime information of the machine in addition to
numpy.show_config
which displays the build-related information.
(gh-21468)
strict
option fortesting.assert_array_equal
The
strict
option is now available fortesting.assert_array_equal
.Setting
strict=True
will disable the broadcasting behaviour forscalars and ensure that input arrays have the same data type.
(gh-21595)
New parameter
equal_nan
added tonp.unique
np.unique
was changed in 1.21 to treat allNaN
values as equal andreturn a single
NaN
. Settingequal_nan=False
will restore pre-1.21behavior to treat
NaNs
as unique. Defaults toTrue
.(gh-21623)
casting
anddtype
keyword arguments fornumpy.stack
The
casting
anddtype
keyword arguments are now available fornumpy.stack
. To use them, writenp.stack(..., dtype=None, casting='same_kind')
.casting
anddtype
keyword arguments fornumpy.vstack
The
casting
anddtype
keyword arguments are now available fornumpy.vstack
. To use them, writenp.vstack(..., dtype=None, casting='same_kind')
.casting
anddtype
keyword arguments fornumpy.hstack
The
casting
anddtype
keyword arguments are now available fornumpy.hstack
. To use them, writenp.hstack(..., dtype=None, casting='same_kind')
.(gh-21627)
The bit generator underlying the singleton RandomState can be changed
The singleton
RandomState
instance exposed in thenumpy.random
module is initialized at startup with the
MT19937
bit generator. Thenew function
set_bit_generator
allows the default bit generator to bereplaced with a user-provided bit generator. This function has been
introduced to provide a method allowing seamless integration of a
high-quality, modern bit generator in new code with existing code that
makes use of the singleton-provided random variate generating functions.
The companion function
get_bit_generator
returns the current bitgenerator being used by the singleton
RandomState
. This is provided tosimplify restoring the original source of randomness if required.
The preferred method to generate reproducible random numbers is to use a
modern bit generator in an instance of
Generator
. The functiondefault_rng
simplifies instantiation:The same bit generator can then be shared with the singleton instance so
that calling functions in the
random
module will use the same bitgenerator:
The swap is permanent (until reversed) and so any call to functions in
the
random
module will use the new bit generator. The original can berestored if required for code to run correctly:
(gh-21976)
np.void
now has adtype
argumentNumPy now allows constructing structured void scalars directly by
passing the
dtype
argument tonp.void
.(gh-22316)
Improvements
F2PY Improvements
API anymore
f2py
generated exception messagesflake8
warning fixessignature files are prefixed with
f2py_
. For example, one shoulduse
f2py_len(x)
instead oflen(x)
character(f2py_len=...)
is introduced to supportreturning assumed length character strings (e.g.
character(len=*)
)from wrapper functions
A hook to support rewriting
f2py
internal data structures afterreading all its input files is introduced. This is required, for
instance, for BC of SciPy support where character arguments are treated
as character strings arguments in
C
expressions.(gh-19388)
IBM zSystems Vector Extension Facility (SIMD)
Added support for SIMD extensions of zSystem (z13, z14, z15), through
the universal intrinsics interface. This support leads to performance
improvements for all SIMD kernels implemented using the universal
intrinsics, including the following operations: rint, floor, trunc,
ceil, sqrt, absolute, square, reciprocal, tanh, sin, cos, equal,
not_equal, greater, greater_equal, less, less_equal, maximum, minimum,
fmax, fmin, argmax, argmin, add, subtract, multiply, divide.
(gh-20913)
NumPy now gives floating point errors in casts
In most cases, NumPy previously did not give floating point warnings or
errors when these happened during casts. For examples, casts like:
Should now generally give floating point warnings. These warnings should
warn that floating point overflow occurred. For errors when converting
floating point values to integers users should expect invalid value
warnings.
Users can modify the behavior of these warnings using
np.errstate
.Note that for float to int casts, the exact warnings that are given may
be platform dependent. For example:
May give a result equivalent to (the intermediate cast means no warning
is given):
May return an undefined result, with a warning set:
The precise behavior is subject to the C99 standard and its
implementation in both software and hardware.
(gh-21437)
F2PY supports the value attribute
The Fortran standard requires that variables declared with the
value
attribute must be passed by value instead of reference. F2PY now
supports this use pattern correctly. So
integer, intent(in), value :: x
in Fortran codes will have correctwrappers generated.
(gh-21807)
Added pickle support for third-party BitGenerators
The pickle format for bit generators was extended to allow each bit
generator to supply its own constructor when during pickling. Previous
versions of NumPy only supported unpickling
Generator
instancescreated with one of the core set of bit generators supplied with NumPy.
Attempting to unpickle a
Generator
that used a third-party bitgenerators would fail since the constructor used during the unpickling
was only aware of the bit generators included in NumPy.
(gh-22014)
arange() now explicitly fails with dtype=str
Previously, the
np.arange(n, dtype=str)
function worked forn=1
andn=2
, but would raise a non-specific exception message for other valuesof
n
. Now, it raises a [TypeError]{.title-ref} informing thatarange
does not support string dtypes:
(gh-22055)
numpy.typing
protocols are now runtime checkableThe protocols used in
numpy.typing.ArrayLike
andnumpy.typing.DTypeLike
are now properly marked as runtime checkable,making them easier to use for runtime type checkers.
(gh-22357)
Performance improvements and changes
Faster version of
np.isin
andnp.in1d
for integer arraysnp.in1d
(used bynp.isin
) can now switch to a faster algorithm (upto >10x faster) when it is passed two integer arrays. This is often
automatically used, but you can use
kind="sort"
orkind="table"
toforce the old or new method, respectively.
(gh-12065)
Faster comparison operators
The comparison functions (
numpy.equal
,numpy.not_equal
,numpy.less
,numpy.less_equal
,numpy.greater
andnumpy.greater_equal
) are now much faster as they are now vectorizedwith universal intrinsics. For a CPU with SIMD extension AVX512BW, the
performance gain is up to 2.57x, 1.65x and 19.15x for integer, float and
boolean data types, respectively (with N=50000).
(gh-21483)
Changes
Better reporting of integer division overflow
Integer division overflow of scalars and arrays used to provide a
RuntimeWarning
and the return value was undefined leading to crashesat rare occasions:
Integer division overflow now returns the input dtype's minimum value
and raise the following
RuntimeWarning
:(gh-21506)
masked_invalid
now modifies the mask in-placeWhen used with
copy=False
,numpy.ma.masked_invalid
now modifies theinput masked array in-place. This makes it behave identically to
masked_where
and better matches the documentation.(gh-22046)
nditer
/NpyIter
allows all allocating all operandsThe NumPy iterator available through
np.nditer
in Python and asNpyIter
in C now supports allocating all arrays. The iterator shapedefaults to
()
in this case. The operands dtype must be provided,since a "common dtype" cannot be inferred from the other inputs.
(gh-22457)
Checksums
MD5
SHA256
v1.23.5
Compare Source
NumPy 1.23.5 Release Notes
NumPy 1.23.5 is a maintenance release that fixes bugs discovered after
the 1.23.4 release and keeps the build infrastructure current. The
Python versions supported for this release are 3.8-3.11.
Contributors
A total of 7 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 10 pull requests were merged for this release.
random.logseries
Checksums
MD5
SHA256
v1.23.4
Compare Source
NumPy 1.23.4 Release Notes
NumPy 1.23.4 is a maintenance release that fixes bugs discovered after
the 1.23.3 release and keeps the build infrastructure current. The main
improvements are fixes for some annotation corner cases, a fix for a
long time
nested_iters
memory leak, and a fix of complex vector dotfor very large arrays. The Python versions supported for this release
are 3.8-3.11.
Note that the mypy version needs to be 0.981+ if you test using Python
3.10.7, otherwise the typing tests will fail.
Contributors
A total of 8 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 13 pull requests were merged for this release.
__array_api_version__
tonumpy.array_api
namespaceget_info
from "extending with Cython"...lookfor
's import try/except againnumpy.typing
protocols as runtime checkableChecksums
MD5
SHA256
v1.23.3
Compare Source
NumPy 1.23.3 Release Notes
NumPy 1.23.3 is a maintenance release that fixes bugs discovered after
the 1.23.2 release. There is no major theme for this release, the main
improvements are for some downstream builds and some annotation corner
cases. The Python versions supported for this release are 3.8-3.11.
Note that we will move to MacOS 11 for the NumPy 1.23.4 release, the
10.15 version currently used will no longer be supported by our build
infrastructure at that point.
Contributors
A total of 16 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 14 pull requests were merged for this release.
__class_getitem__
np.equal.reduce
raises aTypeError
Checksums
MD5
SHA256
v1.23.2
Compare Source
NumPy 1.23.2 Release Notes
NumPy 1.23.2 is a maintenance release that fixes bugs discovered after
the 1.23.1 release. Notable features are:
The Python versions supported for this release are 3.8-3.11.
Contributors
A total of 9 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 15 pull requests were merged for this release.
__array_ufunc__
typing support to thenin=1
ufuncsnp.angle
dtype-overloads_GenericAlias
wrap the underlying classes'...einsum
subscripts to be passed via integer...np.generic
rich comparisonssqueeze
andtranspose
method to...Popen
to silently invoke f77 -vChecksums
MD5
SHA256
v1.23.1
Compare Source
NumPy 1.23.1 Release Notes
The NumPy 1.23.1 is a maintenance release that fixes bugs discovered
after the 1.23.0 release. Notable fixes are:
The Python version supported for this release are 3.8-3.10.
Contributors
A total of 7 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 8 pull requests were merged for this release.
keepdims
during normalization innp.average
and...max_rows
behaviour innp.loadtxt
Checksums
MD5
SHA256
v1.23.0
Compare Source
NumPy 1.23.0 Release Notes
The NumPy 1.23.0 release continues the ongoing work to improve the
handling and promotion of dtypes, increase the execution speed, clarify
the documentation, and expire old deprecations. The highlights are:
loadtxt
in C, greatly improving its performance.See below for the details,
New functions
A masked array specialization of
ndenumerate
is now available asnumpy.ma.ndenumerate
. It provides an alternative tonumpy.ndenumerate
and skips masked values by default.(gh-20020)
numpy.from_dlpack
has been added to allow easy exchange of datausing the DLPack protocol. It accepts Python objects that implement
the
__dlpack__
and__dlpack_device__
methods and returns andarray object which is generally the view of the data of the input
object.
(gh-21145)
Deprecations
Setting
__array_finalize__
toNone
is deprecated. It must now bea method and may wish to call
super().__array_finalize__(obj)
after checking for
None
or if the NumPy version is sufficientlynew.
(gh-20766)
Using
axis=32
(axis=np.MAXDIMS
) in many cases had the samemeaning as
axis=None
. This is deprecated andaxis=None
must beused instead.
(gh-20920)
The hook function
PyDataMem_SetEventHook
has been deprecated andthe demonstration of its use in tool/allocation_tracking has been
removed. The ability to track allocations is now built-in to python
via
tracemalloc
.(gh-20394)
numpy.distutils
has been deprecated, as a result ofdistutils
itself being deprecated. It will not be present in NumPy for
Python >= 3.12, and will be removed completely 2 years after the
release of Python 3.12 For more details, see
distutils-status-migration
{.interpreted-text role="ref"}.(gh-20875)
numpy.loadtxt
will now give aDeprecationWarning
when an integerdtype
is requested but the value is formatted as a floating point number.(gh-21663)
Expired deprecations
The
NpzFile.iteritems()
andNpzFile.iterkeys()
methods have beenremoved as part of the continued removal of Python 2 compatibility.
This concludes the deprecation from 1.15.
(gh-16830)
The
alen
andasscalar
functions have been removed.(gh-20414)
The
UPDATEIFCOPY
array flag has been removed together with theenum
NPY_ARRAY_UPDATEIFCOPY
. The associated (and deprecated)PyArray_XDECREF_ERR
was also removed. These were all deprecated in1.14. They are replaced by
WRITEBACKIFCOPY
, that requires callingPyArray_ResoveWritebackIfCopy
before the array is deallocated.(gh-20589)
Exceptions will be raised during array-like creation. When an object
raised an exception during access of the special attributes
__array__
or__array_interface__
, this exception was usuallyignored. This behaviour was deprecated in 1.21, and the exception
will now be raised.
(gh-20835)
Multidimensional indexing with non-tuple values is not allowed.
Previously, code such as
arr[ind]
whereind = [[0, 1], [0, 1]]
produced a
FutureWarning
and was interpreted as a multidimensionalindex (i.e.,
arr[tuple(ind)]
). Now this example is treated like anarray index over a single dimension (
arr[array(ind)]
).Multidimensional indexing with anything but a tuple was deprecated
in NumPy 1.15.
(gh-21029)
Changing to a dtype of different size in F-contiguous arrays is no
longer permitted. Deprecated since Numpy 1.11.0. See below for an
extended explanation of the effects of this change.
(gh-20722)
New Features
crackfortran has support for operator and assignment overloading
crackfortran
parser now understands operator and assignmentdefinitions in a module. They are added in the
body
list of the modulewhich contains a new key
implementedby
listing the names of thesubroutines or functions implementing the operator or assignment.
(gh-15006)
f2py supports reading access type attributes from derived type statements
As a result, one does not need to use
public
orprivate
statementsto specify derived type access properties.
(gh-15844)
New parameter
ndmin
added togenfromtxt
This parameter behaves the same as
ndmin
fromnumpy.loadtxt
.(gh-20500)
np.loadtxt
now supports quote character and single converter functionnumpy.loadtxt
now supports an additionalquotechar
keyword argumentwhich is not set by default. Using
quotechar='"'
will read quotedfields as used by the Excel CSV dialect.
Further, it is now possible to pass a single callable rather than a
dictionary for the
converters
argument.(gh-20580)
Changing to dtype of a different size now requires contiguity of only the last axis
Previously, viewing an array with a dtype of a different item size
required that the entire array be C-contiguous. This limitation would
unnecessarily force the user to make contiguous copies of non-contiguous
arrays before being able to change the dtype.
This change affects not only
ndarray.view
, but other constructionmechanisms, including the discouraged direct assignment to
ndarray.dtype
.This change expires the deprecation regarding the viewing of
F-contiguous arrays, described elsewhere in the release notes.
(gh-20722)
Deterministic output files for F2PY
For F77 inputs,
f2py
will generatemodname-f2pywrappers.f
unconditionally, though these may be empty. For free-form inputs,
modname-f2pywrappers.f
,modname-f2pywrappers2.f90
will both begenerated unconditionally, and may be empty. This allows writing generic
output rules in
cmake
ormeson
and other build systems. Olderbehavior can be restored by passing
--skip-empty-wrappers
tof2py
.f2py-meson
{.interpreted-text role="ref"} details usage.(gh-21187)
keepdims
parameter foraverage
The parameter
keepdims
was added to the functionsnumpy.average
andnumpy.ma.average
. The parameter has the same meaning as it does inreduction functions such as
numpy.sum
ornumpy.mean
.(gh-21485)
New parameter
equal_nan
added tonp.unique
np.unique
was changed in 1.21 to treat allNaN
values as equal andreturn a single
NaN
. Settingequal_nan=False
will restore pre-1.21behavior to treat
NaNs
as unique. Defaults toTrue
.(gh-21623)
Compatibility notes
1D
np.linalg.norm
preserves float input types, even for scalar resultsPreviously, this would promote to
float64
when theord
argument wasnot one of the explicitly listed values, e.g.
ord=3
:This change affects only
float32
andfloat16
vectors withord
other than
-Inf
,0
,1
,2
, andInf
.(gh-17709)
Changes to structured (void) dtype promotion and comparisons
In general, NumPy now defines correct, but slightly limited, promotion
for structured dtypes by promoting the subtypes of each field instead of
raising an exception:
For promotion matching field names, order, and titles are enforced,
however padding is ignored. Promotion involving structured dtypes now
always ensures native byte-order for all fields (which may change the
result of
np.concatenate
) and ensures that the result will be"packed", i.e. all fields are ordered contiguously and padding is
removed. See
structured_dtype_comparison_and_promotion
{.interpreted-textrole="ref"} for further details.
The
repr
of aligned structures will now never print the long formincluding
offsets
anditemsize
unless the structure includes paddingnot guaranteed by
align=True
.In alignment with the above changes to the promotion logic, the casting
safety has been updated:
"equiv"
enforces matching names and titles. The itemsize isallowed to differ due to padding.
"safe"
allows mismatching field names and titlesfield.
field. Previously, the field names were used and only unsafe casts
were possible when names mismatched.
The main important change here is that name mismatches are now
considered "safe" casts.
(gh-19226)
NPY_RELAXED_STRIDES_CHECKING
has been removedNumPy cannot be compiled with
NPY_RELAXED_STRIDES_CHECKING=0
anymore.Relaxed strides have been the default for many years and the option was
initially introduced to allow a smoother transition.
(gh-20220)
np.loadtxt
has recieved several changesThe row counting of
numpy.loadtxt
was fixed.loadtxt
ignores fullyempty lines in the file, but counted them towards
max_rows
. Whenmax_rows
is used and the file contains empty lines, these will now notbe counted. Previously, it was possible that the result contained fewer
than
max_rows
rows even though more data was available to be read. Ifthe old behaviour is required,
itertools.islice
may be used:While generally much faster and improved,
numpy.loadtxt
may now failto converter certain strings to numbers that were previously
successfully read. The most important cases for this are:
1.0
into integers is nowdeprecated.
0x3p3
will fail_
was previously accepted as a thousands delimiter100_000
.This will now result in an error.
If you experience these limitations, they can all be worked around by
passing appropriate
converters=
. NumPy now supports passing a singleconverter to be used for all columns to make this more convenient. For
example,
converters=float.fromhex
can read hexadecimal float numbersand
converters=int
will be able to read100_000
.Further, the error messages have been generally improved. However, this
means that error types may differ. In particularly, a
ValueError
isnow always raised when parsing of a single entry fails.
(gh-20580)
Improvements
ndarray.__array_finalize__
is now callableThis means subclasses can now use
super().__array_finalize__(obj)
without worrying whether
ndarray
is their superclass or not. Theactual call remains a no-op.
(gh-20766)
Add support for VSX4/Power10
With VSX4/Power10 enablement, the new instructions available in Power
ISA 3.1 can be used to accelerate some NumPy operations, e.g.,
floor_divide, modulo, etc.
(gh-20821)
np.fromiter
now accepts objects and subarraysThe
numpy.fromiter
function now supports object and subarray dtypes.Please see he function documentation for examples.
(gh-20993)
Math C library feature detection now uses correct signatures
Compiling is preceded by a detection phase to determine whether the
underlying libc supports certain math operations. Previously this code
did not respect the proper signatures. Fixing this enables compilation
for the
wasm-ld
backend (compilation for web assembly) and reduces thenumber of warnings.
(gh-21154)
np.kron
now maintains subclass informationnp.kron
maintains subclass information now such as masked arrays whilecomputing the Kronecker product of the inputs
⚠️ Warning,
np.kron
output now followsufunc
ordering (multiply
) to determinethe output class type
(gh-21262)
Performance improvements and changes
Faster
np.loadtxt
numpy.loadtxt
is now generally much faster than previously as most ofit is now implemented in C.
(gh-20580)
Faster reduction operators
Reduction operations like
numpy.sum
,numpy.prod
,numpy.add.reduce
,numpy.logical_and.reduce
on contiguous integer-based arrays are nowmuch faster.
(gh-21001)
Faster
np.where
numpy.where
is now much faster than previously on unpredictable/randominput data.
(gh-21130)
Faster operations on NumPy scalars
Many operations on NumPy scalars are now significantly faster, although
rare operations (e.g. with 0-D arrays rather than scalars) may be slower
in some cases. However, even with these improvements users who want the
best performance for their scalars, may want to convert a known NumPy
scalar into a Python one using
scalar.item()
.(gh-21188)
Faster
np.kron
numpy.kron
is about 80% faster as the product is now computed usingbroadcasting.
(gh-21354)
Checksums
MD5
SHA256
v1.22.4
Compare Source
NumPy 1.22.4 Release Notes
NumPy 1.22.4 is a maintenance release that fixes bugs discovered after
the 1.22.3 release. In addition, the wheels for this release are built
using the recently released Cython 0.29.30, which should fix the
reported problems with
debugging.
The Python versions supported for this release are 3.8-3.10. Note that
the Mac wheels are now based on OS X 10.15 rather than 10.6 that was
used in previous NumPy release cycles.
Contributors
A total of 12 people contributed to this release. People with a "+" by
their names contributed a patch for the first time.
Pull requests merged
A total of 22 pull requests were merged for this release.
np.lib.stride_tricks
re-exported under the...numpy._typing
npy_memchr
withno_sanitize("alignment")
on clangChecksums
MD5
SHA256
Configuration
📅 Schedule: At any time (no schedule defined).
🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.
♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR has been generated by Renovate Bot.
⚠ Artifact update problem
Renovate failed to update an artifact related to this branch. You probably do not want to merge this PR as-is.
♻ Renovate will retry this branch, including artifacts, only when one of the following happens:
The artifact failure details are included below:
File name: poetry.lock
0cd0a4e09a
tocce575a9ef
cce575a9ef
toa86f9bf88e
a86f9bf88e
toa47342ce7e
a47342ce7e
to18c99acdd4
18c99acdd4
to27db2ca5e0
27db2ca5e0
tobd92d58c9f
bd92d58c9f
to0f0472965b
0f0472965b
tofd7d72c87a
fd7d72c87a
toaed66048b8
aed66048b8
tof33b5c7292
f33b5c7292
to3f0f3f19fe
3f0f3f19fe
to044588dc70
044588dc70
tobf3e5b96ca
bf3e5b96ca
tod7121e3b3f
Checkout
From your project repository, check out a new branch and test the changes.