chore(deps): update dependency numpy to v2 #34
Reference in New Issue
Block a user
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.0.0Release Notes
numpy/numpy
v2.3.5Compare Source
NumPy 2.3.5 Release Notes
The NumPy 2.3.5 release is a patch release split between a number of maintenance
updates and bug fixes. This release supports Python versions 3.11-3.14.
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 16 pull requests were merged for this release.
orderparameter docs ofma.asanyarray...v2.3.4Compare Source
NumPy 2.3.4 Release Notes
The NumPy 2.3.4 release is a patch release split between a number of maintenance
updates and bug fixes. This release supports Python versions 3.11-3.14. This
release is based on Python 3.14.0 final.
Changes
The
npymathandnpyrandomlibraries now have a.librather than a.afile extension on win-arm64, for compatibility for building with MSVC andsetuptools. Please note that using these static libraries is discouragedand for existing projects using it, it's best to use it with a matching
compiler toolchain, which is
clang-clon Windows on Arm.(gh-29750)
Contributors
A total of 17 people contributed to this release. People with a "+" by their
names contributed a patch for the first time.
Pull requests merged
A total of 30 pull requests were merged for this release.
dtyperefcount in__array__(#29715)__slots__(#29901)testing._private(#29902)errstate(#29914)@classmethodarg to clsv2.3.3Compare Source
NumPy 2.3.3 Release Notes
The NumPy 2.3.3 release is a patch release split between a number of maintenance
updates and bug fixes. This release supports Python versions 3.11-3.14. Note
that the 3.14.0 final is currently expected in Oct, 2025. This release is based
on 3.14.0rc2.
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 23 pull requests were merged for this release.
sortedkwarg touniquev2.3.2Compare Source
NumPy 2.3.2 Release Notes
The NumPy 2.3.2 release is a patch release with a number of bug fixes
and maintenance updates. The highlights are:
This release supports Python versions 3.11-3.14
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 16 pull requests were merged for this release.
np.char.arrayandnp.char.asarray...squareonarr \*\* 2(#29392)Checksums
MD5
SHA256
v2.3.1Compare 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:
matmulfor non-contiguous out kwarg parameternp.vectorizecasting 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.vectorizecasting to legacy behavior (#29196)Checksums
MD5
SHA256
v2.3.0Compare 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.sliceThe new function
numpy.strings.slicewas 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_pluginhas been deprecated in favor ofplatform-agnostic static type inference. Please remove
numpy.typing.mypy_pluginfrom thepluginssection of your mypyconfiguration. If this change results in new errors being reported,
kindly open an issue.
(gh-28129)
The
numpy.typing.NBitBasetype 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,
float64andcomplex128were 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_OWNDATAfrom Cython interfacesin favor of
NPY_ARRAY_OWNDATA(deprecated since 1.7)(gh-28254)
Remove
numpy/npy_1_7_deprecated_api.hand C macros likeNPY_OWNDATAin favor ofNPY_ARRAY_OWNDATA(deprecated since 1.7)(gh-28254)
Remove alias
generate_divbyzero_errortonpy_set_floatstatus_divbyzeroandgenerate_overflow_errortonpy_set_floatstatus_overflow(deprecated since 1.10)(gh-28254)
Remove
np.tostring(deprecated since 1.19)(gh-28254)
Raise on
np.conjugateof 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=Noneto functions with a non-optional shape argumenterrors, use
()instead (deprecated since 1.20)(gh-28254)
Inexact matches for
modeandsearchsideraise (deprecated since1.20)
(gh-28254)
Setting
__array_finalize__ = Noneerrors (deprecated since 1.23)(gh-28254)
np.fromfileandnp.fromstringerror on bad data, previously theywould guess (deprecated since 1.18)
(gh-28254)
datetime64andtimedelta64construction with a tuple no longeraccepts an
eventvalue, 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
dtypefrom a class with adtypeattribute,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.tostringhas been removed, usetobytesinstead (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=Noneusessame-kindcasting 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
fromstringnow errors, usefrombufferinstead(deprecated since 1.14)
(gh-28254)
Converting
np.inexactornp.floatingto a dtype errors(deprecated since 1.19)
(gh-28254)
Converting
np.complex,np.integer,np.signedinteger,np.unsignedinteger,np.genericto a dtype errors (deprecatedsince 1.19)
(gh-28254)
The Python built-in
rounderrors for complex scalars. Usenp.roundorscalar.roundinstead (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=floatkeyword argument.np.loadtxt(...).astype(np.int64)(gh-28254)
The use of a length 1 tuple for the ufunc
signatureerrors. Usedtypeor 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.compatpackage source code (removed in 2.0)(gh-28961)
C API changes
NpyIter_GetTransferFlagsis 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)
NpyIternow has no limit on the number of operands it supports.(gh-28080)
New
NpyIter_GetTransferFlagsandNpyIter_IterationNeedsAPIchangeNumPy now has the new
NpyIter_GetTransferFlagsfunction 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_IterationNeedsAPIfunction 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.dtypenow defaults totyping.Any. Thisway, static type-checkers will infer
dtype: np.dtypeasdtype: np.dtype[Any], without reporting an error.(gh-28669)
Static type-checkers now interpret:
_: np.ndarrayas_: npt.NDArray[typing.Any]._: np.flatiteras_: 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
outnot 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=trueMeson build flag. This feature isdisabled by default. When enabled,
np.sortandnp.argsortfunctionscan 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.nditernow 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
kindanditemsize.(gh-28250)
np.dotnow reports floating point exceptions.(gh-28442)
np.dtypes.StringDTypeis now a generictype which
accepts a type argument for
na_objectthat defaults totyping.Never. For example,StringDType(na_object=None)returns aStringDType[None], andStringDType()returns aStringDType[typing.Never].(gh-28856)
Added warnings to
np.iscloseAdded warning messages if at least one of atol or rtol are either
np.nanornp.infwithinnp.isclose.np.seterrsettings(gh-28205)
Performance improvements and changes
Performance improvements to
np.uniquenp.uniquenow 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
sortedparameter to allow returningunique values as they were found, instead of sorting them afterwards.
(gh-26018)
Performance improvements to
np.sortandnp.argsortnp.sortandnp.argsortfunctions 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.float16castsEarlier, floating point casts to and from
np.float16types 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=infand 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_positionalhasbeen fixed.
(gh-28569)
NumPy's
__array_api_version__was upgraded from2023.12to2024.12.numpy.count_nonzeroforaxis=None(default) now returns a NumPyscalar instead of a Python integer.
The parameter
axisinnumpy.take_along_axisfunction has now adefault value of
-1.(gh-28615)
Printing of
np.float16andnp.float32scalars and arrays havebeen improved by adjusting the transition to scientific notation
based on the floating point precision. A new legacy
np.printoptionsmode'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_valuesmay return unsorted dataThe relatively new function (added in NumPy 2.0)
unique_valuesmay nowreturn unsorted results. Just as
unique_countsandunique_allthesenever 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.nditerfromPython and
NpyIterin C, now behaves differently for some bufferediterations. This means that:
sized allowed by the
buffersizeparameter.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
einsumto 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.histogramhas 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
binor
rangeparameters ofnumpy.histogram.(gh-28426)
Build manylinux_2_28 wheels
Wheels for linux systems will use the
manylinux_2_28tag (instead ofthe
manylinux2014tag), 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.stringsRe-enable overriding functions in the
numpy.stringsmodule.(gh-28741)
Checksums
MD5
SHA256
v2.2.6Compare 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] + floatreturn typeCanIndexannotation inndarray.setfieldChecksums
MD5
SHA256
v2.2.5Compare 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.stringsndarray.tolist()and.item()for unknown dtypewrite()tostrinsavetxt"b1"literals fordtype[bool]NDArray[object_].__abs__()NDArray[float64].__[r]truediv__return...ndarrayrich comparison operators[arg]partitionfixesrandom.Generator.integersreturn typecount_nonzerosignatureChecksums
MD5
SHA256
v2.2.4Compare 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.3Compare 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_positionalerrors for huge padsfloat64in the set-opstimedelta64.__divmod__andtimedelta64.__mod__...numpy.matlibnumpy.testingmodulesTYP:PR's and issuesChecksums
MD5
SHA256
v2.2.2Compare 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.
voidarrays not acceptingstrkeys in__setitem__integerbinop return types (#28065)ndarraybinop return types forfloat64&...boolfromissubdtypedate[time]in thedatetime64constructorinterpto accept and return scalarsChecksums
MD5
SHA256
v2.2.1Compare 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"Nonein operand sequence of nditerChecksums
MD5
SHA256
v2.2.0Compare 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:
matvecandvecmat, see below.This release supports Python versions 3.10-3.13.
Deprecations
_add_newdoc_ufuncis now deprecated.ufunc.__doc__ = newdocshould be used instead.
(gh-27735)
Expired deprecations
bool(np.array([]))and other empty arrays will now raise an error.Use
arr.size > 0instead to check whether an array has noelements.
(gh-27160)
Compatibility notes
numpy.covnow 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.matmulas well as tonumpy.vecdot, which was added in numpy 2.0.Note that
numpy.matmulnever takes a complexconjugate, also not when its left input is a vector, while both
numpy.vecdotandnumpy.vecmatdo 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.numberand its subtypes nowdefaults to
typing.Any. This way, type-checkers will inferannotations such as
x: np.floatingasx: np.floating[Any], evenin strict mode.
(gh-27736)
Improvements
The
datetime64andtimedelta64hashes now correctly match thePythons builtin
datetimeandtimedeltaones. 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 emptymemmapwould fail unless a non-zerooffsetwas set.Now a zero-size
memmapis supported even ifoffset=0. To achieve this, if amemmapis 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.zerosallocationson linux. Thus should generally improve performance.
(gh-27808)
Changes
numpy.fixnow won't perform casting to a floatingdata-type for integer and boolean data-type input arrays.
(gh-26766)
The type annotations of
numpy.float64andnumpy.complex128nowreflect that they are also subtypes of the built-in
floatandcomplextypes, respectively. This update prevents statictype-checkers from reporting errors in cases such as:
(gh-27334)
The
reprof arrays large enough to be summarized (i.e., whereelements are replaced with
...) now includes theshapeof 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.arrayconstructor. If you encounter problems, e.g., dueto failing doctests, you can use the print option
legacy=2.1toget the old behaviour.
(gh-27482)
Calling
__array_wrap__directly on NumPy arrays or scalars nowdoes the right thing when
return_scalaris 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=weakwhile
_set_promotion_stateand_get_promotion_stateare removed. Incase code used
_no_nep50_warning, acontextlib.nullcontextcould beused to replace it when not available.
(gh-27156)
Checksums
MD5
SHA256
v2.1.3Compare 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.fixnow 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.
pythonto 3.12 in environment.ymlChecksums
MD5
SHA256
v2.1.2Compare 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.1Compare 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.0Compare 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.unstackA 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_importskeyword argument innumpy.saveis deprecated.Since NumPy 1.17,
numpy.saveuses a pickle protocol that no longersupports Python 2, and ignored
fix_importskeyword. 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.nonzeroandnumpy.ndarray.nonzero.(gh-26268)
set_string_functioninternal function was removed andPyArray_SetStringFunctionwas 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_APIorPyArray_RUNTIME_VERSION, you can define theNPY_API_SYMBOL_ATTRIBUTEto 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
PyUFuncObjectfieldprocess_core_dims_funcThe field
process_core_dims_funcwas added to the structurePyUFuncObject. For generalized ufuncs, this field can be set to afunction of type
PyUFunc_ProcessCoreDimsFuncthat 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
resizemethod 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)
f2pycan generate freethreading-compatible C extensionsPass
--freethreading-compatibleto 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
f2pydoes 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.reshapeandnumpy.ndarray.reshapenow supportshapeandcopyarguments.(gh-26292)
NumPy now supports DLPack v1, support for older versions will be
deprecated in the future.
(gh-26501)
numpy.asanyarraynow supportscopyanddevicearguments,matching
numpy.asarray.(gh-26580)
numpy.printoptions,numpy.get_printoptions, andnumpy.set_printoptionsnow support a new option,override_repr,for defining custom
repr(array)behavior.(gh-26611)
numpy.cumulative_sumandnumpy.cumulative_prodwere added asArray API compatible alternatives for
numpy.cumsumandnumpy.cumprod. The new functions can include a fixed initial(zeros for
sumand ones forprod) in the result.(gh-26724)
numpy.clipnow supportsmaxandminkeyword arguments whichare meant to replace
a_minanda_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.astypenow supportsdeviceargument.(gh-26724)
Improvements
histogramauto-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)
ndarrayshape-type parameter is now covariant and bound totuple[int, ...]Static typing for
ndarrayis 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.quantilewith methodclosest_observationchooses 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_liteis now thread safeNumPy provides a minimal low-performance version of LAPACK named
lapack_litethat can be used if no BLAS/LAPACK system is detected atbuild time.
Until now,
lapack_litewas 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_liteinmultiple threads.
(gh-26750)
The
numpy.printoptionscontext 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.polynomialStarting from the 2.1 release, PEP 484 type annotations have been
included for the functions and convenience classes in
numpy.polynomialand its sub-packages.
(gh-26897)
Improved
numpy.dtypestype hintsThe type annotations for
numpy.dtypesare now a better reflection ofthe runtime: The
numpy.dtypetype-aliases have been replaced withspecialized
dtypesubtypes, and the previously missing annotationsfor
numpy.dtypes.StringDTypehave been added.(gh-27008)
Performance improvements and changes
numpy.savenow 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.covandma.corrcoefare now significantly fasterThe private function has been refactored along with
ma.covandma.corrcoef. They are now significantly faster, particularly on large,masked arrays.
(gh-26285)
Changes
As
numpy.vecdotis 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.truncnow won't performcasting to a floating dtype for integer and boolean dtype input
arrays.
(gh-26766)
ma.corrcoefmay return a slightly different resultA pairwise observation approach is currently used in
ma.corrcoeftocalculate 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
corrcoefwhen using a masked array with no masked values.
(gh-26285)
Cast-safety fixes in
copytoandfullcopytonow 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_likewith the correct NumPy 2behavior.
(gh-27091)
Checksums
MD5
SHA256
v2.0.2Compare 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.
alltrueandsometruenpyv_loadable_stride_functions for ldexp and...np.saveChecksums
MD5
SHA256
v2.0.1Compare 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.quantilewith methodclosest_observationchooses 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.pyistubset_printoptionsloadtxtPyArray_FillWithScalarChecksums
MD5
SHA256
v2.0.0Compare 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.StringDTypeand a newnumpy.stringsnamespace with performant ufuncs for string operations,float32andlongdoublein allnumpy.fftfunctions,numpynamespace.
sort,argsort,partition,argpartitionhave 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.charfixed-length string operations havebeen accelerated by implementing ufuncs that also support
numpy.dtypes.StringDTypein 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.savenow 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.libby ~80%.Canonical dtype names and a newnumpy.isdtype` introspectionfunction,
internals hidden to ease future extensibility,
PyArray_ImportNumPyAPIand
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.
int64rather 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
ruffmode 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
ImportErrorwith 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.seterrobjand 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.casthas been removed. The literal replacement fornp.cast[dtype](arg)isnp.asarray(arg, dtype=dtype).np.sourcehas been removed. The preferred replacement isinspect.getsource.np.lookforhas been removed.(gh-24144)
numpy.whohas 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.oldnumericandnp.set_numeric_ops.(gh-24316)
Replaced
from ... import *in thenumpy/__init__.pywithexplicit 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_docstringandnp.add_newdoc_ufunc.(gh-24357)
Alias
np.float_has been removed. Usenp.float64instead.Alias
np.complex_has been removed. Usenp.complex128instead.Alias
np.longfloathas been removed. Usenp.longdoubleinstead.Alias
np.singlecomplexhas been removed. Usenp.complex64instead.
Alias
np.cfloathas been removed. Usenp.complex128instead.Alias
np.longcomplexhas been removed. Usenp.clongdoubleinstead.
Alias
np.clongfloathas been removed. Usenp.clongdoubleinstead.
Alias
np.string_has been removed. Usenp.bytes_instead.Alias
np.unicode_has been removed. Usenp.str_instead.Alias
np.Infhas been removed. Usenp.infinstead.Alias
np.Infinityhas been removed. Usenp.infinstead.Alias
np.NaNhas been removed. Usenp.naninstead.Alias
np.inftyhas been removed. Usenp.infinstead.Alias
np.mathas been removed. Usenp.asmatrixinstead.np.issubclass_has been removed. Use theissubclassbuiltininstead.
np.asfarrayhas been removed. Usenp.asarraywith a proper dtypeinstead.
np.set_string_functionhas been removed. Usenp.set_printoptionsinstead with a formatter for custom printing of NumPy objects.
np.tracemalloc_domainis now only available fromnp.lib.np.recfromcsvandrecfromtxtare now only available fromnp.lib.npyio.np.issctype,np.maximum_sctype,np.obj2sctype,np.sctype2char,np.sctypes,np.issubsctypewere all removedfrom the main namespace without replacement, as they where niche
members.
Deprecated
np.deprecateandnp.deprecate_with_dochas beenremoved from the main namespace. Use
DeprecationWarninginstead.Deprecated
np.safe_evalhas been removed from the main namespace.Use
ast.literal_evalinstead.(gh-24376)
np.find_common_typehas been removed. Usenumpy.promote_typesornumpy.result_typeinstead. To achieve semantics for thescalar_typesargument, usenumpy.result_typeand pass0,0.0, or0jas a Python scalar instead.np.round_has been removed. Usenp.roundinstead.np.nbyteshas been removed. Usenp.dtype(<dtype>).itemsizeinstead.
(gh-24477)
np.compare_chararrayshas been removed from the main namespace.Use
np.char.compare_chararraysinstead.The
charrarrayin the main namespace has been deprecated. It canbe imported without a deprecation warning from
np.char.chararrayfor now, but we are planning to fully deprecate and remove
chararrayin the future.np.format_parserhas been removed from the main namespace. Usenp.rec.format_parserinstead.(gh-24587)
Support for seven data type string aliases has been removed from
np.dtype:int0,uint0,void0,object0,str0,bytes0and
bool8.(gh-24807)
The experimental
numpy.array_apisubmodule has been removed. Usethe main
numpynamespace for regular usage instead, or theseparate
array-api-strictpackage for the compliance testing usecase for which
numpy.array_apiwas 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.compathas been deprecated, as Python 2 is no longer supported.numpy.int8and 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_evalhas been deprecated.ast.literal_evalshould beused instead.
(gh-23830)
np.recfromcsv,np.recfromtxt,np.disp,np.get_array_wrap,np.maximum_sctype,np.deprecateandnp.deprecate_with_dochavebeen deprecated.
(gh-24154)
np.trapzhas been deprecated. Usenp.trapezoidor ascipy.integratefunction instead.np.in1dhas been deprecated. Usenp.isininstead.Alias
np.row_stackhas been deprecated. Usenp.vstackdirectly.(gh-24445)
__array_wrap__is now passedarr, context, return_scalarandsupport 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.crosshave 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
xandywith functionsassert_array_equalandassert_array_almost_equalhas beendeprecated. Pass the first two arguments as positional arguments
instead.
(gh-24978)
numpy.fftdeprecations for n-D transforms with None values in argumentsUsing
fftn,ifftn,rfftn,irfftn,fft2,ifft2,rfft2orirfft2with thesparameter set to a value that is notNoneandthe
axesparameter set toNonehas been deprecated, in line with thearray API standard. To retain current behaviour, pass a sequence [0,
..., k-1] to
axesfor an array of dimension k.Furthermore, passing an array to
swhich containsNonevalues 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
nparameter. To use the default behaviourfor every axis, the
sargument can be omitted.(gh-25495)
np.linalg.lstsqnow defaults to a newrcondvaluenumpy.linalg.lstsqnow 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_testssubmodule has been removed from the publicAPI. (Deprecated in NumPy 1.15)
(gh-23809)
The
PyDataMem_SetEventHookdeprecation has expired and it isremoved. Use
tracemallocand thenp.lib.tracemalloc_domaindomain. (Deprecated in NumPy 1.23)
(gh-23921)
The deprecation of
set_numeric_opsand the C functionsPyArray_SetNumericOpsandPyArray_GetNumericOpshas been expiredand the functions removed. (Deprecated in NumPy 1.16)
(gh-23998)
The
fasttake,fastclip, andfastputmaskArrFuncsdeprecationis now finalized.
The deprecated function
fastCopyAndTransposeand its C counterpartare now removed.
The deprecation of
PyArray_ScalarFromObjectis now finalized.(gh-24312)
np.msorthas 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
.dataattribute of an ndarray is disallowed andwill raise.
np.binary_repr(a, width)will raise if width is too small.Using
NPY_CHARinPyArray_DescrFromType()will raise, useNPY_STRINGNPY_UNICODE, orNPY_VSTRINGinstead.(gh-25794)
Compatibility notes
loadtxtandgenfromtxtdefault encoding changedloadtxtandgenfromtxtnow both default toencoding=Nonewhich maymainly modify how
converterswork. These will now be passedstrrather than
bytes. Pass the encoding explicitly to always get the newor old behavior. For
genfromtxtthe change also means that returnedvalues will now be unicode strings rather than bytes.
(gh-25158)
f2pycompatibility notesf2pywill no longer accept ambiguous-mand.pyfCLIcombinations. When more than one
.pyffile is passed, an error israised. When both
-mand a.pyfis passed, a warning is emittedand the
-mprovided 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.runwrapper. It was also oneof the test bottlenecks. See
gh-25122 for the full
rationale. It also used several
np.distutilsfeatures which aretoo fragile to be ported to work with
meson.Users are urged to replace calls to
f2py.compilewith 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.argsortandnumpy.argpartition.Removed ambiguity when broadcasting in
np.solveThe broadcasting rules for
np.solve(a, b)were ambiguous whenbhad1 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
PolynomialThe representation method for
numpy.polynomial.polynomial.Polynomialwas 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_CNEmacros have been removed.PyArray_MINandPyArray_MAXhave been moved fromndarraytypes.htonpy_math.h.(gh-24258)
A C API for working with
numpy.dtypes.StringDTypearrays 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_NTYPEShas been renamed toNPY_NTYPES_LEGACYas 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_Packto set an individual memory address.Unlike
PyArray_SETITEMthis function is equivalent to setting anindividual array item and does not require a NumPy array input.
(gh-25954)
The
->fslot 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_GETITEMmay be an alternatives.PyArray_GETITEMandPyArray_SETITEMnow 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.handis only available after including
numpy/ndarrayobject.has itrequires
import_array(). This includesPyDataType_FLAGCHK,PyDataType_REFCHKandNPY_BEGIN_THREADS_DESCR.The dtype flags on
PyArray_Descrmust now be accessed through thePyDataType_FLAGSinline function to be compatible with both 1.xand 2.x. This function is defined in
npy_2_compat.hto allowbackporting. Most or all users should use
PyDataType_FLAGCHKwhichis 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_FLAGCHKinstead.(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_ParseISO8601Datetimehave 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) taketypesanddataarguments that are not modified by NumPy's internals. Like thenameanddocarguments, third-party Python extension modules arelikely to supply these arguments from static constants. The
typesanddataarguments are now const-correct: they are declared asconst char *typesandvoid *const *data, respectively. C code shouldnot be affected, but C++ code may be.
(gh-23847)
Larger
NPY_MAXDIMSandNPY_MAXARGS,NPY_RAVEL_AXISintroducedNPY_MAXDIMSis 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_MAXDIMSandNPY_MAXARGSto eventually allow removing the constraint completely.For the conversion helper and C-API functions mirroring Python ones such as
take,NPY_MAXDIMSwas used to meanaxis=None. Such usage must be replacedwith
NPY_RAVEL_AXIS. See alsomigration_maxdims.(gh-25149)
NPY_MAXARGSnot constant andPyArrayMultiIterObjectsize changeSince
NPY_MAXARGSwas 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_MAXARGSas 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_RegisterDataTypefor 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-apifor 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_ImportNumPyAPIandPyUFunc_ImportUFuncAPIas static inline functions to import the NumPy C-API tables. The new
functions have two advantages over
import_arrayandimport_ufunc:light-weight if not, allowing to add them judiciously (although this
is not preferable in most cases).
a
returnstatement.The
PyArray_ImportNumPyAPI()function is included innpy_2_compat.hfor simpler backporting.
(gh-25866)
Structured dtype information access through functions
The dtype structures fields
c_metadata,names,fields, andsubarraymust 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_Descrinstances. Themetadatafield is kept, but the macro version should also bepreferred.
(gh-25802)
Descriptor
elsizeandalignmentaccessUnless compiling only with NumPy 2 support, the
elsizeandaligmentfields 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_ITEMSIZEas it exists on all NumPy versions. Please see
migration_c_descrfor more information.(gh-25943)
NumPy 2.0 C API removals
npy_interrupt.hand the corresponding macros likeNPY_SIGINT_ONhave been removed. We recommend querying
PyErr_CheckSignals()orPyOS_InterruptOccurred()periodically (these do currently requireholding the GIL though).
The
noprefix.hheader has been removed. Replace missing symbolswith their prefixed counterparts (usually an added
NPY_ornpy_).(gh-23919)
PyUFunc_GetPyVals,PyUFunc_handlefperr, andPyUFunc_checkfperrhave 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.hwhich 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_CONSTANTversion.(gh-24011)
The
legacy_inner_loop_selectormember 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_INTPLTRhas been removed to avoid confusion (seeintpredefinition).
(gh-24888)
The advanced indexing
MapIterand 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_ELSIZEmacro has been removed, as it only everreflected builtin numeric types and served no internal purpose.
(gh-25149)
PyArray_REFCNTandNPY_REFCOUNTare removed. UsePy_REFCNTinstead.
(gh-25156)
PyArrayFlags_TypeandPyArray_NewFlagsObjectas well asPyArrayFlagsObjectare private now. There is no known use-case;use the Python API if needed.
PyArray_MoveInto,PyArray_CastTo,PyArray_CastAnyToareremoved use
PyArray_CopyIntoand if absolutely neededPyArray_CopyAnyInto(the latter does a flat copy).PyArray_FillObjectArrayis removed, its only true use was forimplementing
np.empty. Create a new empty array or usePyArray_FillWithScalar()(decrefs existing objects).PyArray_CompareUCS4andPyArray_CompareStringare removed. Usethe standard C string comparison functions.
PyArray_ISPYTHONis removed as it is misleading, has no knownuse-cases, and is easy to replace.
PyArray_FieldNamesis removed, as it is unclear what it would beuseful for. It also has incorrect semantics in some possible
use-cases.
PyArray_TypestrConvertis 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_GetDatetimeMetaDatais removed, it did not actually doanything since at least NumPy 1.7.
(gh-25802)
PyArray_GetCastFuncis 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.addwas extended to work withunicodeandbytesdtypes.A new
bitwise_countfunctionThis new function counts the number of 1-bits in a number.
numpy.bitwise_countworks 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
weightskeyword is now available fornumpy.quantile,numpy.percentile,numpy.nanquantileandnumpy.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_infohas 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
f2pyf2pyin compile mode (i.e.f2py -c) now accepts the--backend mesonoption. This is the default option for Python >=3.12.For older Python versions,
f2pywill still default to--backend distutils.To support this in realistic use-cases, in compile mode
f2pytakes a--depflag one or many times which maps todependency()calls in themesonbackend, and does nothing in thedistutilsbackend.There are no changes for users of
f2pyonly as a code generator, i.e.without
-c.(gh-24532)
bind(c)support forf2pyBoth functions and subroutines can be annotated with
bind(c).f2pywill 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
f2pybindings by design, sincebind(c)with thenameis meant to guarantee only the same name in C and Fortran, not inPython and Fortran.
(gh-24555)
A new
strictoption for several testing functionsThe
strictkeyword is now available fornumpy.testing.assert_allclose,numpy.testing.assert_equal, andnumpy.testing.assert_array_less. Settingstrict=Truewill 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.findandnp.core.umath.rfindUFuncsAdd two
findandrfindUFuncs that operate on unicode or bytestrings and are used in
np.char. They operate similar tostr.findand
str.rfind.(gh-24868)
diagonalandtracefornumpy.linalgnumpy.linalg.diagonalandnumpy.linalg.tracehave been added, which arearray API standard-compatible variants of
numpy.diagonalandnumpy.trace.They differ in the default axis selection which define 2-D sub-arrays.
(gh-24887)
New
longandulongdtypesnumpy.longandnumpy.ulonghave been added as NumPy integers mapping toC's
longandunsigned long. Prior to NumPy 1.24,numpy.longwas an aliasto Python's
int.(gh-24922)
svdvalsfornumpy.linalgnumpy.linalg.svdvalshas 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
isdtypefunctionnumpy.isdtypewas added to provide a canonical way to classify NumPy'sdtypes in compliance with the array API standard.
(gh-25054)
A new
astypefunctionnumpy.astypewas added to provide an array API standard-compatiblealternative to the
numpy.ndarray.astypemethod.(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_valuesfunctions have been added. They provide functionality ofnumpy.uniquewith 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.ndarrayandnp.ma.MaskedArraynow expose a.mTattribute, and there is amatching new
numpy.matrix_transposefunction.(gh-23762)
Array API compatible functions for
numpy.linalgSix 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.outerhas been added. It computes theouter product of two vectors. It differs from
numpy.outerby accepting one-dimensional arrays only.This function is compatible with the array API standard.
(gh-25101)
numpy.linalg.crosshas been added. It computes thecross product of two (arrays of) 3-dimensional vectors. It differs
from
numpy.crossby accepting three-dimensionalvectors only. This function is compatible with the array API
standard.
(gh-25145)
A
correctionargument forvarandstdA
correctionargument was added tonumpy.varandnumpy.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.deviceandndarray.to_deviceAn
ndarray.deviceattribute andndarray.to_devicemethod were addedto
numpy.ndarrayfor array API standard compatibility.Additionally,
devicekeyword-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
choleskyandpinvThe
upperandrtolkeywords were added tonumpy.linalg.choleskyandnumpy.linalg.pinv,respectively, to improve array API standard compatibility.
For
numpy.linalg.pinv, if neitherrcondnorrtolisspecified, the
rcond's default is used. We plan to deprecate andremove
rcondin the future.(gh-25388)
New keywords for
sort,argsortandlinalg.matrix_rankNew keyword parameters were added to improve array API standard
compatibility:
rtolwas added tonumpy.linalg.matrix_rank.stablewas added tonumpy.sortandnumpy.argsort.(gh-25437)
New
numpy.stringsnamespace for string ufuncsNumPy now implements some string operations as ufuncs. The old
np.charnamespace 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.stringsinstead ofnp.char. In the future we may deprecatenp.charin favor ofnp.strings.(gh-25463)
numpy.fftsupport for different precisions and in-place calculationsThe various FFT routines in
numpy.fftnow 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
outargument that can beused for in-place calculations.
(gh-25536)
configtool and pkg-config support
A new
numpy-configCLI 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.pcpkg-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
numpynamespace now supports the array API standard. Seearray-api-standard-compatibilityfordetails.
(gh-25911)
Improvements
Strings are now supported by
any,all, and the logical ufuncs.Integer sequences as the shape argument for
memmapnumpy.memmapcan now be created with any integer sequenceas the
shapeargument, 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)
errstateis now faster and context safeThe
numpy.errstatecontext 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.realorc.imag) is no longer an option. You cannow use utilities provided in
numpy/npy_math.hto 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-numbersfor more info.numpy/npy_common.hnow includescomplex.h, which means thatcomplexis now a reserved keyword.(gh-24085)
iso_c_bindingsupport and improved common blocks forf2pyPreviously, users would have to define their own custom
f2cmapfile touse type mappings defined by the Fortran2003
iso_c_bindingintrinsicmodule. These type maps are now natively supported by
f2py(gh-24555)
f2pynow handlescommonblocks which havekindspecifications frommodules. This further expands the usability of intrinsics like
iso_fortran_envandiso_c_binding.(gh-25186)
Call
strautomatically on third argument to functions likeassert_equalThe third argument to functions like
numpy.testing.assert_equalnow hasstrcalled on itautomatically. This way it mimics the built-in
assertstatement, whereassert_equal(a, b, obj)works likeassert a == b, obj.(gh-24877)
Support for array-like
atol/rtolinisclose,allcloseThe keywords
atolandrtolinnumpy.iscloseandnumpy.allclosenow 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.testingassertions printed messagesthat referred to the actual and desired results as
xandy. Now,these values are consistently referred to as
ACTUALandDESIRED.(gh-24931)
n-D FFT transforms allow
s[i] == -1The
numpy.fft.fftn,numpy.fft.ifftn,numpy.fft.rfftn,numpy.fft.irfftn,numpy.fft.fft2,numpy.fft.ifft2,numpy.fft.rfft2andnumpy.fft.irfft2functions now use the whole input array along the axis
iifs[i] == -1, in line with the array API standard.(gh-25495)
Guard PyArrayScalar_VAL and PyUnicodeScalarObject for the limited API
PyUnicodeScalarObjectholds aPyUnicodeObject, which is notavailable when using
Py_LIMITED_API. Add guards to hide it andconsequently also make the
PyArrayScalar_VALmacro 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.errstatecan only beentered once now.
np.setbufsizeis now tied tonp.errstate(): leaving annp.errstatecontext will also reset thebufsize.(gh-23936)
A new public
np.lib.array_utilssubmodule has been introduced andit currently contains three functions:
byte_bounds(moved fromnp.lib.utils),normalize_axis_tupleandnormalize_axis_index.(gh-24540)
Introduce
numpy.boolas the new canonical name forNumPy's boolean dtype, and make
numpy.bool\_an aliasto it. Note that until NumPy 1.24,
np.boolwas an alias toPython's builtin
bool. The new name helps with array API standardcompatibility and is a more intuitive name.
(gh-25080)
The
dtype.flagsvalue 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
TrueorFalseand the definition did not match the oneused by Python. Strings are now considered
Truewhen they arenon-empty and
Falsewhen 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
Truesince 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 ever0or1). 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, whilegenfromtxtcontinues to match for"true"(ignoring case). However,if
np.bool_is used as a converter the result will change.The change does affect
np.fromregexas it uses direct assignments.(gh-23871)
A
meankeyword 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.varandnumpy.stdfunctions 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.datetime64method 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.coretonumpy._coreAccessing
numpy.corenow emits a DeprecationWarning. In practice wehave found that most downstream usage of
numpy.corewas to accessfunctionality that is available in the main
numpynamespace. If forsome reason you are using functionality in
numpy.corethat is notavailable in the main
numpynamespace, this means you are likely usingprivate NumPy internals. You can still access these internals via
numpy._corewithout 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_DEBUGenvironment variable or the-Drelaxed-strides-debugconfig-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_tthis is now the definition in C. Previously, itmatched
intptr_tanduintptr_twhich 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:
intptyped array anymore.The
pandPcharacter codes can still be used, however.intptr_toruintptr_ttyped arrays in C remainspossible in a cross-platform way via
PyArray_DescrFromType('p').nNwere introduced.npy_intptyped arguments.(gh-24888)
numpy.fft.helpermade privatenumpy.fft.helperwas renamed tonumpy.fft._helperto indicate thatit is a private submodule. All public functions exported by it should be
accessed from
numpy.fft.(gh-24945)
numpy.linalg.linalgmade privatenumpy.linalg.linalgwas renamed tonumpy.linalg._linalgto 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=NoneIn some cases
axis=32or for concatenate any large value was the sameas
axis=None. Except forconcatenatethis was deprecate. Any out ofbound axis value will now error, make sure to use
axis=None.(gh-25149)
New
copykeyword meaning forarrayandasarrayconstructorsNow
numpy.arrayandnumpy.asarraysupportthree values for
copyparameter: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 aValueErrorisraised.
The meaning of
Falsechanged as it now raises an exception if a copyis needed.
(gh-25168)
The
__array__special method now takes acopykeyword argument.NumPy will pass
copyto 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
copykeyword argument. Implementations ofobjects implementing the
__array__protocol should accept acopykeyword argument with the same meaning as when passed to
numpy.arrayornumpy.asarray.(gh-25168)
Cleanup of initialization of
numpy.dtypewith 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.uniquereturn_inverseshape for multi-dimensional inputsWhen multi-dimensional inputs are passed to
np.uniquewithreturn_inverse=True, theunique_inverseoutput 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)
anyandallreturn booleans for object arraysThe
anyandallfunctions and methods now return booleans also forobject arrays. Previously, they did a reduction which behaved like the
Python
orandandoperators which evaluates to one of the arguments.You can use
np.logical_or.reduceandnp.logical_and.reducetoachieve the previous behavior.
(gh-25712)
np.can_castcannot be called on Python int, float, or complexnp.can_castcannot be called with Python int, float, or complexinstances anymore. This is because NEP 50 means that the result of
can_castmust 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.4Compare 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.choleskyupper decomp...newaxisto__all__innumpy.array_api__config__.pyChecksums
MD5
SHA256
v1.26.3Compare 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
f2pywill no longer accept ambiguous-mand.pyfCLI combinations.When more than one
.pyffile is passed, an error is raised. When both-mand a.pyfis passed, a warning is emitted and the-mprovidedname is ignored.
Improvements
f2pynow handlescommonblocks which havekindspecifications frommodules. This further expands the usability of intrinsics like
iso_fortran_envandiso_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_apinewaxisandlinalg.solveinnumpy.array_apilongtypebasein cpu_avx512_knf2pywrappers when modules and subroutines...iso_c_typemappings more consistentlyf2pyrewrite withmesondetailsnumpy/f2py/_backendsfrom main.f2py/*.pyfrom main.Checksums
MD5
SHA256
v1.26.2Compare 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()noexceptto shuffle helpersallow-noblasoption to true.np.dtypeto itself doesn't crashChecksums
MD5
SHA256
v1.26.1Compare 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
piporpypa/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-configorCMake.
Besides
-Dblasand-Dlapack, a number of other new flags areavailable to control BLAS/LAPACK selection and behavior:
-Dblas-orderand-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,gompandtbb. 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._coresubmodule stubsnumpy._coresubmodule 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-creditsfor Cirrus.NumpyUnpicklerfor backportingnumpy._corestubs. RemoveNumpyUnpicklerChecksums
MD5
SHA256
v1.26.0Compare 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_apinumpy.array_apinow full supports thev2022.12 version of the array API standard. Note that this does not
yet include the optional
fftextension 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)
mesonbackend forf2pyf2pyin compile mode (i.e.f2py -c) now accepts the--backend mesonoption. This is the default option for Python3.12on-wards. Older versions will still default to
--backend distutils.To support this in realistic use-cases, in compile mode
f2pytakes a--depflag one or many times which maps todependency()calls in themesonbackend, and does nothing in thedistutilsbackend.There are no changes for users of
f2pyonly as a code generator, i.e.without
-c.(gh-24532)
bind(c)support forf2pyBoth functions and subroutines can be annotated with
bind(c).f2pywill handle both the correct type mapping, and preserve the unique label
for other
Cinterfaces.Note:
bind(c, name = 'routine_name_other_than_fortran_routine')isnot honored by the
f2pybindings by design, sincebind(c)with thenameis meant to guarantee only the same name inCandFortran,not in
PythonandFortran.(gh-24555)
Improvements
iso_c_bindingsupport forf2pyPreviously, users would have to define their own custom
f2cmapfile touse type mappings defined by the Fortran2003
iso_c_bindingintrinsicmodule. 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
pipandpypa/build. Thefollowing are supported:
pip install numpyor (in a cloned repo)pip install .python -m build(preferred), orpip wheel .pip install -e . --no-build-isolationspin:
spin build.All the regular
pipandpypa/buildflags (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.cfgfile 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.txtfile 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.tomlfor 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.setuppytopyproject.toml. However, please open anissue with details on the NumPy issue tracker. We aim to phase out
setup.pybuilds 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.pyfrom main.asv devhas been removed, useasv run._umath_linalgdependenciesbindingdirective to "False".castingkeyword tonp.clipfromnumeric.pyiiso_c_bindingtype maps and fixbind(c)...binary_reprto accept any object implementing...dtypeandgenerichashabletyping.assert_typemesonbackend forf2pyspin docs...Checksums
MD5
SHA256
v1.25.2Compare 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-mathwith Clang on macOSnp.__all__getenvcall used for memory policy warningChecksums
MD5
SHA256
v1.25.1Compare 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 NULLto begoto fail__array_ufunc__works without any kwargs passedChecksums
MD5
SHA256
v1.25.0Compare 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.MachAris deprecated. It is private API. In names definedin
np.coreshould generally be considered private.(gh-22638)
np.finfo(None)is deprecated.(gh-23011)
np.round_is deprecated. Usenp.roundinstead.(gh-23302)
np.productis deprecated. Usenp.prodinstead.(gh-23314)
np.cumproductis deprecated. Usenp.cumprodinstead.(gh-23314)
np.sometrueis deprecated. Usenp.anyinstead.(gh-23314)
np.alltrueis deprecated. Usenp.allinstead.(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_typeis now deprecated and its useshould be replaced with either
numpy.result_typeornumpy.promote_types. Most users leave the secondscalar_typesargument tofind_common_typeas[]in which casenp.result_typeandnp.promote_typesare both faster and morerobust. When not using
scalar_typesthe main difference is thatthe replacement intentionally converts non-native byte-order to
native byte order. Further,
find_common_typereturnsobjectdtype 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_typesargument is not[]things are morecomplicated. In most cases, using
np.result_typeand passing thePython values
0,0.0, or0jhas the same result as usingint,float, orcomplexinscalar_types.When
scalar_typesis constructed,np.result_typeis 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_typenever 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_typesorwhen non-numeric dtypes are likely, please do not hesitate to open a
NumPy issue to ask for help.
(gh-22539)
Expired deprecations
np.core.macharandnp.finfo.macharhave been removed.(gh-22638)
+arrwill 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,dstackandcolumn_stack).(gh-23019)
np.clipnow defaults to same-kind casting. Falling back to unsafecasting was deprecated in NumPy 1.17.
(gh-23403)
np.clipwill now propagatenp.nanvalues passed asminormax. Previously, a scalar NaN was usually ignored. This wasdeprecated in NumPy 1.17.
(gh-23403)
The
np.dualsubmodule 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
FutureWarningwhen casting to a subarray dtype inastypeor the array creation functions such asasarrayis 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
Trueor allFalsewhen 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
FalseandTruewhen comparing incompatible types like
"a" == 1and"a" != 1. For a long time these gaveDeprecationWarningorFutureWarning.(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.utilsshim has been removed. Importing from thenumpy.testing.utilsshim 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_FUNCTIONenvironmentvariable has been removed. This variable disabled dispatching with
__array_function__.(gh-23376)
Support for
y=as an alias ofout=has been removed. Thefix,isposinfandisneginffunctions allowed usingy=as a(deprecated) alias for
out=. This is no longer supported.(gh-23376)
Compatibility notes
The
busday_countmethod now correctly handles cases where thebegindatesis later in time than theenddates. Previously, theenddateswas included, even though the documentation states it isalways excluded.
(gh-23229)
When comparing datetimes and timedelta using
np.equalornp.not_equalnumpy previously allowed the comparison withcasting="unsafe". This operation now fails. Forcing the outputdtype using the
dtypekwarg 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.loadrepeatedly, numpy previously raisedValueErrorif
allow_pickle=False, andOSErrorifallow_pickle=True. Nowit raises
EOFErrorinstead, in both cases.(gh-23105)
np.padwithmode=wrappads with strict multiples of original dataCode based on earlier version of
padthat usesmode="wrap"willreturn different results when the padding size is larger than initial
array.
np.padwithmode=wrapnow always fills the space with strictmultiples of original data even if the padding size is larger than the
initial array.
(gh-22575)
Cython
long_tandulong_tremovedlong_tandulong_twere aliases forlonglong_tandulonglong_tand 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_tor the use ofcnp.intp_twhich is 32 bits on 32 bit systems and 64 bits on 64 bitsystems (this is most compatible with indexing). If C
longis desired,use plain
longornpy_long.cnp.int_tis alsolong(NumPy'sdefault integer). However,
longis 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
axesargument toufuncThe error message and type when a wrong
axesvalue is passed toufunc(..., axes=[...])has changed. The message is now moreindicative of the problem, and if the value is mismatched an
AxisErrorwill be raised. ATypeErrorwill still be raised forinvalidinput types.
(gh-22675)
Array-likes that define
__array_ufunc__can now override ufuncs if used aswhereIf the
wherekeyword 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 thewhereargument to pass it into the default implementation of the
ufuncor,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-numpyunnecessary.Libraries can override the default minimal version to be compatible with
using:
before including NumPy or by passing the equivalent
-Doption 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.einsumnow accepts arrays withobjectdtypeThe code path will call python operators on object dtype arrays, much
like
np.dotandnp.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_FEATURESenvironment variableUsers may now choose to enable only a subset of the built CPU features
at runtime by specifying the
NPY_ENABLE_CPU_FEATURESenvironment 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.exceptionsnamespaceNumPy 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.linalgfunctions return NamedTuplesnp.linalgfunctions 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.charare 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
NDArrayOperatorsMixinspecifies that it has no__slots__The
NDArrayOperatorsMixinclass 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.powernow 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+0jor0-0j.(gh-18535)
New
DTypePromotionErrorNumPy now has a new
DTypePromotionErrorwhich is used when two dtypescannot be promoted to a common one, for example:
raises this new exception.
(gh-22707)
np.show_configuses information from MesonBuild and system information now contains information from Meson.
np.show_confignow has a new optional parametermodetohelp customize the output.
(gh-22769)
Fix
np.ma.diffnot preserving the mask when called with arguments prepend/append.Calling
np.ma.diffwith arguments prepend and/or append now returns aMaskedArraywith the input mask preserved.Previously, a
MaskedArraywithout 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 -1orexcept *. These have nowbeen added.
(gh-22997)
Ability to directly spawn random number generators
numpy.random.Generator.spawnnow allows to directly spawn new independentchild generators via the
numpy.random.SeedSequence.spawnmechanism.numpy.random.BitGenerator.spawndoes the same for the underlying bitgenerator.
Additionally,
numpy.random.BitGenerator.seed_seqnow 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
SeedSequenceexplicitly. Please see
numpy.random.SeedSequencefor moreinformation.
(gh-23195)
numpy.logspacenow supports a non-scalarbaseargumentThe
baseargument ofnumpy.logspacecan now be array-like if it isbroadcastable against the
startandstoparguments.(gh-23275)
np.ma.dot()now supports for non-2d arraysPreviously
np.ma.dot()only worked ifaandbwere both 2d. Now itworks for non-2d arrays as well as
np.dot().(gh-23322)
Explicitly show keys of .npz file in repr
NpzFileshows keys of loaded .npz file when printed.(gh-23357)
NumPy now exposes DType classes in
np.dtypesThe new
numpy.dtypesmodule 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
*.npyfile containing a table with a dtype with metadata cannotbe read back. Now,
np.saveandnp.savezdrop metadata before saving.(gh-23371)
numpy.lib.recfunctions.structured_to_unstructuredreturns views in more casesstructured_to_unstructurednow 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,memmapandrecarray. For all other array subclasses, the behaviorremains unchanged.
(gh-23652)
Signed and unsigned integers always compare correctly
When
uint64andint64are 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.argsorton 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.sorton 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.atcan be much fasterGeneric
ufunc.atcan be up to 9x faster. The conditions for thisspeedup:
If ufuncs with appropriate indexed loops on 1d arguments with the above
conditions,
ufunc.atcan 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
NpzFileMembership test on
NpzFilewill 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
255not fitting intoint8andNumPy 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_umathextension is linked with the C++ linker.(gh-23601)
Checksums
MD5
SHA256
v1.24.4Compare 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.
metadataparameter of...Checksums
MD5
SHA256
v1.24.3Compare 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.dargument to fftfreq and rfftfreq as optional...msortlike=dispatched functionsorder="A"ororder="K"Checksums
MD5
SHA256
v1.24.2Compare 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.
_Alignofrather thanoffsetof()on most compilersAnyparameter to thenpt.ArrayLike...Checksums
MD5
SHA256
v1.24.1Compare 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.0Compare 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.fastCopyAndTransposefunction has been deprecated. Use thecorresponding copy and transpose methods directly:
The underlying C function
PyArray_CopyAndTransposehas 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
DeprecationWarningnow: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).maxorval % 2**8may also work well.In rare cases input data may mix both negative values and very large
unsigned values (i.e.
-1and2**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
msortThe
numpy.msortfunction is deprecated. Usenp.sort(a, axis=0)instead.
(gh-22456)
np.str0and similar are now deprecatedThe scalar type aliases ending in a 0 bit size:
np.object0,np.str0,np.bytes0,np.void0,np.int0,np.uint0as well asnp.bool8arenow deprecated and will eventually be removed.
(gh-22607)
Expired deprecations
The
normedkeyword argument has been removed from[np.histogram]{.title-ref}, [np.histogram2d]{.title-ref}, and
[np.histogramdd]{.title-ref}. Use
densityinstead. Ifnormedwaspassed by position,
densityis now used.(gh-21645)
Ragged array creation will now always raise a
ValueErrorunlessdtype=objectis 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.MaskedArrayhas been removed. Useeither
np.ma.MaskedArray.min()ornp.ma.minimum.reduce().The single-argument form of
np.ma.minimumandnp.ma.maximumhasbeen 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.int8since 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
boolandobjectare valid values anddtype=objectis enforced.(gh-22541)
The deprecation for the aliases
np.object,np.bool,np.float,np.complex,np.str, andnp.intis 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.fillmay 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
dtypeor whenthe target had
objectdtype.(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
dtypekeyword 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
longandlonglongare the same precision but differentdtypes:Before the change, the
dtypedid not match becausenew is arrwasTrue.(gh-21995)
DLPack export raises
BufferErrorWhen an array buffer cannot be exported via DLPack a
BufferErrorisnow always raised where previously
TypeErrororRuntimeErrorwasraised. 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
symboladded to polynomial classesThe polynomial classes in the
numpy.polynomialpackage have a newsymbolattribute 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
characterstringsF2PY 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_runtimeA new function
numpy.show_runtimehas been added to display theruntime information of the machine in addition to
numpy.show_configwhich displays the build-related information.
(gh-21468)
strictoption fortesting.assert_array_equalThe
strictoption is now available fortesting.assert_array_equal.Setting
strict=Truewill disable the broadcasting behaviour forscalars and ensure that input arrays have the same data type.
(gh-21595)
New parameter
equal_nanadded tonp.uniquenp.uniquewas changed in 1.21 to treat allNaNvalues as equal andreturn a single
NaN. Settingequal_nan=Falsewill restore pre-1.21behavior to treat
NaNsas unique. Defaults toTrue.(gh-21623)
castinganddtypekeyword arguments fornumpy.stackThe
castinganddtypekeyword arguments are now available fornumpy.stack. To use them, writenp.stack(..., dtype=None, casting='same_kind').castinganddtypekeyword arguments fornumpy.vstackThe
castinganddtypekeyword arguments are now available fornumpy.vstack. To use them, writenp.vstack(..., dtype=None, casting='same_kind').castinganddtypekeyword arguments fornumpy.hstackThe
castinganddtypekeyword 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
RandomStateinstance exposed in thenumpy.randommodule is initialized at startup with the
MT19937bit generator. Thenew function
set_bit_generatorallows 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_generatorreturns 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_rngsimplifies instantiation:The same bit generator can then be shared with the singleton instance so
that calling functions in the
randommodule will use the same bitgenerator:
The swap is permanent (until reversed) and so any call to functions in
the
randommodule will use the new bit generator. The original can berestored if required for code to run correctly:
(gh-21976)
np.voidnow has adtypeargumentNumPy now allows constructing structured void scalars directly by
passing the
dtypeargument tonp.void.(gh-22316)
Improvements
F2PY Improvements
API anymore
f2pygenerated exception messagesflake8warning 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
f2pyinternal 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
Cexpressions.(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
valueattribute must be passed by value instead of reference. F2PY now
supports this use pattern correctly. So
integer, intent(in), value :: xin 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
Generatorinstancescreated with one of the core set of bit generators supplied with NumPy.
Attempting to unpickle a
Generatorthat 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=1andn=2, but would raise a non-specific exception message for other valuesof
n. Now, it raises a [TypeError]{.title-ref} informing thatarangedoes not support string dtypes:
(gh-22055)
numpy.typingprotocols are now runtime checkableThe protocols used in
numpy.typing.ArrayLikeandnumpy.typing.DTypeLikeare 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.isinandnp.in1dfor 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.greaterandnumpy.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
RuntimeWarningand 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_invalidnow modifies the mask in-placeWhen used with
copy=False,numpy.ma.masked_invalidnow modifies theinput masked array in-place. This makes it behave identically to
masked_whereand better matches the documentation.(gh-22046)
nditer/NpyIterallows all allocating all operandsThe NumPy iterator available through
np.nditerin Python and asNpyIterin 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.5Compare 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.logseriesChecksums
MD5
SHA256
v1.23.4Compare 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_itersmemory 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_apinamespaceget_infofrom "extending with Cython"...lookfor's import try/except againnumpy.typingprotocols as runtime checkableChecksums
MD5
SHA256
v1.23.3Compare 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.reduceraises aTypeErrorChecksums
MD5
SHA256
v1.23.2Compare 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=1ufuncsnp.angledtype-overloads_GenericAliaswrap the underlying classes'...einsumsubscripts to be passed via integer...np.genericrich comparisonssqueezeandtransposemethod to...Popento silently invoke f77 -vChecksums
MD5
SHA256
v1.23.1Compare 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.
keepdimsduring normalization innp.averageand...max_rowsbehaviour innp.loadtxtChecksums
MD5
SHA256
v1.23.0Compare 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:
loadtxtin C, greatly improving its performance.See below for the details,
New functions
A masked array specialization of
ndenumerateis now available asnumpy.ma.ndenumerate. It provides an alternative tonumpy.ndenumerateand skips masked values by default.(gh-20020)
numpy.from_dlpackhas 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__toNoneis deprecated. It must now bea method and may wish to call
super().__array_finalize__(obj)after checking for
Noneor 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=Nonemust beused instead.
(gh-20920)
The hook function
PyDataMem_SetEventHookhas 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.distutilshas been deprecated, as a result ofdistutilsitself 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.loadtxtwill now give aDeprecationWarningwhen an integerdtypeis 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
alenandasscalarfunctions have been removed.(gh-20414)
The
UPDATEIFCOPYarray flag has been removed together with theenum
NPY_ARRAY_UPDATEIFCOPY. The associated (and deprecated)PyArray_XDECREF_ERRwas also removed. These were all deprecated in1.14. They are replaced by
WRITEBACKIFCOPY, that requires callingPyArray_ResoveWritebackIfCopybefore 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
FutureWarningand 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
crackfortranparser now understands operator and assignmentdefinitions in a module. They are added in the
bodylist of the modulewhich contains a new key
implementedbylisting 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
publicorprivatestatementsto specify derived type access properties.
(gh-15844)
New parameter
ndminadded togenfromtxtThis parameter behaves the same as
ndminfromnumpy.loadtxt.(gh-20500)
np.loadtxtnow supports quote character and single converter functionnumpy.loadtxtnow supports an additionalquotecharkeyword 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
convertersargument.(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,
f2pywill generatemodname-f2pywrappers.funconditionally, though these may be empty. For free-form inputs,
modname-f2pywrappers.f,modname-f2pywrappers2.f90will both begenerated unconditionally, and may be empty. This allows writing generic
output rules in
cmakeormesonand other build systems. Olderbehavior can be restored by passing
--skip-empty-wrapperstof2py.f2py-meson{.interpreted-text role="ref"} details usage.(gh-21187)
keepdimsparameter foraverageThe parameter
keepdimswas added to the functionsnumpy.averageandnumpy.ma.average. The parameter has the same meaning as it does inreduction functions such as
numpy.sumornumpy.mean.(gh-21485)
New parameter
equal_nanadded tonp.uniquenp.uniquewas changed in 1.21 to treat allNaNvalues as equal andreturn a single
NaN. Settingequal_nan=Falsewill restore pre-1.21behavior to treat
NaNsas unique. Defaults toTrue.(gh-21623)
Compatibility notes
1D
np.linalg.normpreserves float input types, even for scalar resultsPreviously, this would promote to
float64when theordargument wasnot one of the explicitly listed values, e.g.
ord=3:This change affects only
float32andfloat16vectors withordother 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
reprof aligned structures will now never print the long formincluding
offsetsanditemsizeunless 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_CHECKINGhas been removedNumPy cannot be compiled with
NPY_RELAXED_STRIDES_CHECKING=0anymore.Relaxed strides have been the default for many years and the option was
initially introduced to allow a smoother transition.
(gh-20220)
np.loadtxthas recieved several changesThe row counting of
numpy.loadtxtwas fixed.loadtxtignores fullyempty lines in the file, but counted them towards
max_rows. Whenmax_rowsis used and the file contains empty lines, these will now notbe counted. Previously, it was possible that the result contained fewer
than
max_rowsrows even though more data was available to be read. Ifthe old behaviour is required,
itertools.islicemay be used:While generally much faster and improved,
numpy.loadtxtmay now failto converter certain strings to numbers that were previously
successfully read. The most important cases for this are:
1.0into integers is nowdeprecated.
0x3p3will 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.fromhexcan read hexadecimal float numbersand
converters=intwill be able to read100_000.Further, the error messages have been generally improved. However, this
means that error types may differ. In particularly, a
ValueErrorisnow 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
ndarrayis 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.fromiternow accepts objects and subarraysThe
numpy.fromiterfunction 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-ldbackend (compilation for web assembly) and reduces thenumber of warnings.
(gh-21154)
np.kronnow maintains subclass informationnp.kronmaintains subclass information now such as masked arrays whilecomputing the Kronecker product of the inputs
⚠️ Warning,
np.kronoutput now followsufuncordering (multiply) to determinethe output class type
(gh-21262)
Performance improvements and changes
Faster
np.loadtxtnumpy.loadtxtis 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.reduceon contiguous integer-based arrays are nowmuch faster.
(gh-21001)
Faster
np.wherenumpy.whereis 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.kronnumpy.kronis about 80% faster as the product is now computed usingbroadcasting.
(gh-21354)
Checksums
MD5
SHA256
v1.22.4Compare 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_tricksre-exported under the...numpy._typingnpy_memchrwithno_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
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.