NumPy 1.11.0 Release Notes#

This release supports Python 2.6 - 2.7 and 3.2 - 3.5 and contains a numberof enhancements and improvements. Note also the build system changes listedbelow as they may have subtle effects.

No Windows (TM) binaries are provided for this release due to a brokentoolchain. One of the providers of Python packages for Windows (TM) is yourbest bet.

Highlights#

Details of these improvements can be found below.

  • The datetime64 type is now timezone naive.

  • A dtype parameter has been added torandint.

  • Improved detection of two arrays possibly sharing memory.

  • Automatic bin size estimation fornp.histogram.

  • Speed optimization of A @ A.T and dot(A, A.T).

  • New functionnp.moveaxis for reordering array axes.

Build System Changes#

  • Numpy now usessetuptools for its builds instead of plain distutils.This fixes usage ofinstall_requires='numpy' in thesetup.py files ofprojects that depend on Numpy (see gh-6551). It potentially affects the waythat build/install methods for Numpy itself behave though. Please report anyunexpected behavior on the Numpy issue tracker.

  • Bento build support and related files have been removed.

  • Single file build support and related files have been removed.

Future Changes#

The following changes are scheduled for Numpy 1.12.0.

  • Support for Python 2.6, 3.2, and 3.3 will be dropped.

  • Relaxed stride checking will become the default. See the 1.8.0 releasenotes for a more extended discussion of what this change implies.

  • The behavior of the datetime64 “not a time” (NaT) value will be changedto match that of floating point “not a number” (NaN) values: allcomparisons involving NaT will return False, except for NaT != NaT whichwill return True.

  • Indexing with floats will raise IndexError,e.g., a[0, 0.0].

  • Indexing with non-integer array_like will raiseIndexError,e.g.,a['1','2']

  • Indexing with multiple ellipsis will raiseIndexError,e.g.,a[...,...].

  • Non-integers used as index values will raiseTypeError,e.g., inreshape,take, and specifying reduce axis.

In a future release the following changes will be made.

  • Therand function exposed innumpy.testing will be removed. Thatfunction is left over from early Numpy and was implemented using thePython random module. The random number generators fromnumpy.randomshould be used instead.

  • Thendarray.view method will only allow c_contiguous arrays to beviewed using a dtype of different size causing the last dimension tochange. That differs from the current behavior where arrays that aref_contiguous but not c_contiguous can be viewed as a dtype type ofdifferent size causing the first dimension to change.

  • Slicing aMaskedArray will return views of both dataand mask.Currently the mask is copy-on-write and changes to the mask in the slice donot propagate to the original mask. See the FutureWarnings section below fordetails.

Compatibility notes#

datetime64 changes#

In prior versions of NumPy the experimental datetime64 type always storedtimes in UTC. By default, creating a datetime64 object from a string orprinting it would convert from or to local time:

# old behavior>>>np.datetime64('2000-01-01T00:00:00')numpy.datetime64('2000-01-01T00:00:00-0800')# note the timezone offset -08:00

A consensus of datetime64 users agreed that this behavior is undesirableand at odds with how datetime64 is usually used (e.g., bypandas). For most use cases, a timezone naive datetimetype is preferred, similar to thedatetime.datetime type in the Pythonstandard library. Accordingly, datetime64 no longer assumes that input is inlocal time, nor does it print local times:

>>>np.datetime64('2000-01-01T00:00:00')numpy.datetime64('2000-01-01T00:00:00')

For backwards compatibility, datetime64 still parses timezone offsets, whichit handles by converting to UTC. However, the resulting datetime is timezonenaive:

>>>np.datetime64('2000-01-01T00:00:00-08')DeprecationWarning: parsing timezone aware datetimes is deprecated;this will raise an error in the futurenumpy.datetime64('2000-01-01T08:00:00')

As a corollary to this change, we no longer prohibit casting between datetimeswith date units and datetimes with time units. With timezone naive datetimes,the rule for casting from dates to times is no longer ambiguous.

linalg.norm return type changes#

The return type of thelinalg.norm function is now floating point withoutexception. Some of the norm types previously returned integers.

polynomial fit changes#

The various fit functions in the numpy polynomial package no longer acceptnon-integers for degree specification.

np.dot now raisesTypeError instead ofValueError#

This behaviour mimics that of other functions such asnp.inner. If the twoarguments cannot be cast to a common type, it could have raised aTypeErrororValueError depending on their order. Now,np.dot will now alwaysraise aTypeError.

FutureWarning to changed behavior#

  • Innp.lib.split an empty array in the result always had dimension(0,) no matter the dimensions of the array being split. Thishas been changed so that the dimensions will be preserved. AFutureWarning for this change has been in place since Numpy 1.9 but,due to a bug, sometimes no warning was raised and the dimensions werealready preserved.

% and// operators#

These operators are implemented with theremainder andfloor_dividefunctions respectively. Those functions are now based aroundfmod and arecomputed together so as to be compatible with each other and with the Pythonversions for float types. The results should be marginally more accurate oroutright bug fixes compared to the previous results, but they maydiffer significantly in cases where roundoff makes a difference in the integerreturned byfloor_divide. Some corner cases also change, for instance, NaNis always returned for both functions when the divisor is zero,divmod(1.0,inf) returns(0.0,1.0) except on MSVC 2008, anddivmod(-1.0,inf) returns(-1.0,inf).

C API#

Removed thecheck_return andinner_loop_selector members ofthePyUFuncObject struct (replacing them withreserved slotsto preserve struct layout). These were never used for anything, soit’s unlikely that any third-party code is using them either, but wemention it here for completeness.

object dtype detection for old-style classes#

In python 2, objects which are instances of old-style user-defined classes nolonger automatically count as ‘object’ type in the dtype-detection handler.Instead, as in python 3, they may potentially count as sequences, but only ifthey define both a__len__ and a__getitem__ method. This fixes a segfaultand inconsistency between python 2 and 3.

New Features#

  • np.histogram now provides plugin estimators for automaticallyestimating the optimal number of bins. Passing one of [‘auto’, ‘fd’,‘scott’, ‘rice’, ‘sturges’] as the argument to ‘bins’ results in thecorresponding estimator being used.

  • A benchmark suite usingAirspeed Velocity has been added, converting theprevious vbench-based one. You can run the suite locally viapythonruntests.py--bench. For more details, seebenchmarks/README.rst.

  • A new functionnp.shares_memory that can check exactly whether twoarrays have memory overlap is added.np.may_share_memory also now hasan option to spend more effort to reduce false positives.

  • SkipTest andKnownFailureException exception classes are exposedin thenumpy.testing namespace. Raise them in a test function to markthe test to be skipped or mark it as a known failure, respectively.

  • f2py.compile has a newextension keyword parameter that allows thefortran extension to be specified for generated temp files. For instance,the files can be specifies to be*.f90. Theverbose argument isalso activated, it was previously ignored.

  • Adtype parameter has been added tonp.random.randintRandom ndarrays of the following types can now be generated:

    • np.bool_,

    • np.int8,np.uint8,

    • np.int16,np.uint16,

    • np.int32,np.uint32,

    • np.int64,np.uint64,

    • np.int_``,``np.intp

    The specification is by precision rather than by C type. Hence, on someplatformsnp.int64 may be along instead oflonglong even ifthe specified dtype islonglong because the two may have the sameprecision. The resulting type depends on which C type numpy uses for thegiven precision. The byteorder specification is also ignored, thegenerated arrays are always in native byte order.

  • A newnp.moveaxis function allows for moving one or more array axesto a new position by explicitly providing source and destination axes.This function should be easier to use than the currentrollaxisfunction as well as providing more functionality.

  • Thedeg parameter of the variousnumpy.polynomial fits has beenextended to accept a list of the degrees of the terms to be included inthe fit, the coefficients of all other terms being constrained to zero.The change is backward compatible, passing a scalardeg will behaveas before.

  • A divmod function for float types modeled after the Python version hasbeen added to the npy_math library.

Improvements#

np.gradient now supports anaxis argument#

Theaxis parameter was added tonp.gradient for consistency. Itallows to specify over which axes the gradient is calculated.

np.lexsort now supports arrays with object data-type#

The function now internally calls the genericnpy_amergesort when thetype does not implement a merge-sort kind ofargsort method.

np.ma.core.MaskedArray now supports anorder argument#

When constructing a newMaskedArray instance, it can be configured withanorder argument analogous to the one when callingnp.ndarray. Theaddition of this argument allows for the proper processing of anorderargument in several MaskedArray-related utility functions such asnp.ma.core.array andnp.ma.core.asarray.

Memory and speed improvements for masked arrays#

Creating a masked array withmask=True (resp.mask=False) now usesnp.ones (resp.np.zeros) to create the mask, which is faster andavoid a big memory peak. Another optimization was done to avoid a memorypeak and useless computations when printing a masked array.

ndarray.tofile now uses fallocate on linux#

The function now uses the fallocate system call to reserve sufficientdisk space on file systems that support it.

Optimizations for operations of the formA.T@A andA@A.T#

Previously,gemm BLAS operations were used for all matrix products. Now,if the matrix product is between a matrix and its transpose, it will usesyrk BLAS operations for a performance boost. This optimization has beenextended to@,numpy.dot,numpy.inner, andnumpy.matmul.

Note: Requires the transposed and non-transposed matrices to share data.

np.testing.assert_warns can now be used as a context manager#

This matches the behavior ofassert_raises.

Speed improvement for np.random.shuffle#

np.random.shuffle is now much faster for 1d ndarrays.

Changes#

Pyrex support was removed fromnumpy.distutils#

The methodbuild_src.generate_a_pyrex_source will remain available; ithas been monkeypatched by users to support Cython instead of Pyrex. It’srecommended to switch to a better supported method of build Cythonextensions though.

np.broadcast can now be called with a single argument#

The resulting object in that case will simply mimic iteration overa single array. This change obsoletes distinctions like

if len(x) == 1:

shape = x[0].shape

else:

shape = np.broadcast(*x).shape

Instead,np.broadcast can be used in all cases.

np.trace now respects array subclasses#

This behaviour mimics that of other functions such asnp.diagonal andensures, e.g., that for masked arraysnp.trace(ma) andma.trace() givethe same result.

np.dot now raisesTypeError instead ofValueError#

This behaviour mimics that of other functions such asnp.inner. If the twoarguments cannot be cast to a common type, it could have raised aTypeErrororValueError depending on their order. Now,np.dot will now alwaysraise aTypeError.

linalg.norm return type changes#

Thelinalg.norm function now does all its computations in floating pointand returns floating results. This change fixes bugs due to integer overflowand the failure of abs with signed integers of minimum value, e.g., int8(-128).For consistency, floats are used even where an integer might work.

Deprecations#

Views of arrays in Fortran order#

The F_CONTIGUOUS flag was used to signal that views using a dtype thatchanged the element size would change the first index. This was alwaysproblematical for arrays that were both F_CONTIGUOUS and C_CONTIGUOUSbecause C_CONTIGUOUS took precedence. Relaxed stride checking results inmore such dual contiguous arrays and breaks some existing code as a result.Note that this also affects changing the dtype by assigning to the dtypeattribute of an array. The aim of this deprecation is to restrict views toC_CONTIGUOUS arrays at some future time. A work around that is backwardcompatible is to usea.T.view(...).T instead. A parameter may also beadded to the view method to explicitly ask for Fortran order views, butthat will not be backward compatible.

Invalid arguments for array ordering#

It is currently possible to pass in arguments for theorderparameter in methods likearray.flatten orarray.ravelthat were not one of the following: ‘C’, ‘F’, ‘A’, ‘K’ (note thatall of these possible values are both unicode and case insensitive).Such behavior will not be allowed in future releases.

Random number generator in thetesting namespace#

The Python standard library random number generator was previously exposedin thetesting namespace astesting.rand. Using this generator isnot recommended and it will be removed in a future release. Use generatorsfromnumpy.random namespace instead.

Random integer generation on a closed interval#

In accordance with the Python C API, which gives preference to the half-openinterval over the closed one,np.random.random_integers is beingdeprecated in favor of callingnp.random.randint, which has beenenhanced with thedtype parameter as described under “New Features”.However,np.random.random_integers will not be removed anytime soon.

FutureWarnings#

Assigning to slices/views ofMaskedArray#

Currently a slice of a masked array contains a view of the original data and acopy-on-write view of the mask. Consequently, any changes to the slice’s maskwill result in a copy of the original mask being made and that new mask beingchanged rather than the original. For example, if we make a slice of theoriginal like so,view=original[:], then modifications to the data in onearray will affect the data of the other but, because the mask will be copiedduring assignment operations, changes to the mask will remain local. A similarsituation occurs when explicitly constructing a masked array usingMaskedArray(data,mask), the returned array will contain a view ofdatabut the mask will be a copy-on-write view ofmask.

In the future, these cases will be normalized so that the data and mask arraysare treated the same way and modifications to either will propagate betweenviews. In 1.11, numpy will issue aMaskedArrayFutureWarning warningwhenever user code modifies the mask of a view that in the future may causevalues to propagate back to the original. To silence these warnings and makeyour code robust against the upcoming changes, you have two options: if youwant to keep the current behavior, callmasked_view.unshare_mask() beforemodifying the mask. If you want to get the future behavior early, usemasked_view._sharedmask=False. However, note that setting the_sharedmask attribute will break following explicit calls tomasked_view.unshare_mask().

On this page