Numpy Reference
Numpy Reference
Release 2.0.0.dev8464
1 Array objects 3
1.1 The N-dimensional array (ndarray) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
1.3 Data type objects (dtype) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
1.4 Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
1.5 Standard array subclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
1.6 Masked arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
1.7 The Array Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
3 Routines 389
3.1 Array creation routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
3.2 Array manipulation routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
3.3 Indexing routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
3.4 Data type routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
3.5 Input and output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
3.6 Discrete Fourier Transform (numpy.fft) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
3.7 Linear algebra (numpy.linalg) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
3.8 Random sampling (numpy.random) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
3.9 Sorting and searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
3.10 Logic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
3.11 Binary operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
3.12 Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
3.13 Mathematical functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
3.14 Functional programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
3.15 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
3.16 Financial functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
3.17 Set routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
3.18 Window functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
3.19 Floating point error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
3.20 Masked array operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
i
3.21 Numpy-specific help functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943
3.22 Miscellaneous routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 945
3.23 Test Support (numpy.testing) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
3.24 Asserts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
3.25 Mathematical functions with automatic domain (numpy.emath) . . . . . . . . . . . . . . . . . . . 957
3.26 Matrix library (numpy.matlib) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
3.27 Optionally Scipy-accelerated routines (numpy.dual) . . . . . . . . . . . . . . . . . . . . . . . . . 957
3.28 Numarray compatibility (numpy.numarray) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
3.29 Old Numeric compatibility (numpy.oldnumeric) . . . . . . . . . . . . . . . . . . . . . . . . . . 958
3.30 C-Types Foreign Function Interface (numpy.ctypeslib) . . . . . . . . . . . . . . . . . . . . . . 958
3.31 String operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
7 Acknowledgements 1085
Bibliography 1087
Index 1097
ii
NumPy Reference, Release 2.0.0.dev8464
Release
2.0.dev8464
Date
June 20, 2010
This reference manual details functions, modules, and objects included in Numpy, describing what they are and what
they do. For learning how to use NumPy, see also NumPy User Guide (in NumPy User Guide).
CONTENTS 1
NumPy Reference, Release 2.0.0.dev8464
2 CONTENTS
CHAPTER
ONE
ARRAY OBJECTS
NumPy provides an N-dimensional array type, the ndarray, which describes a collection of items of the same type.
The items can be indexed using for example N integers.
All ndarrays are homogenous: every item takes up the same size block of memory, and all blocks are interpreted in
exactly the same way. How each item in the array is to be interpreted is specified by a separate data-type object, one
of which is associated with every array. In addition to basic types (integers, floats, etc.), the data type objects can also
represent data structures.
An item extracted from an array, e.g., by indexing, is represented by a Python object whose type is one of the array
scalar types built in Numpy. The array scalars allow easy manipulation of also more complicated arrangements of
data.
Figure 1.1: Figure Conceptual diagram showing the relationship between the three fundamental objects used to de-
scribe the data in an array: 1) the ndarray itself, 2) the data-type object that describes the layout of a single fixed-size
element of the array, 3) the array-scalar Python object that is returned when a single element of the array is accessed.
An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. The number
of dimensions and items in an array is defined by its shape, which is a tuple of N positive integers that specify
the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype), one of
which is associated with each ndarray.
As with other container objects in Python, the contents of an ndarray can be accessed and modified by indexing
or slicing the array (using, for example, N integers), and via the methods and attributes of the ndarray. Different
3
NumPy Reference, Release 2.0.0.dev8464
ndarrays can share the same data, so that changes made in one ndarray may be visible in another. That is, an
ndarray can be a view to another ndarray, and the data it is referring to is taken care of by the base ndarray.
ndarrays can also be views to memory owned by Python strings or objects implementing the buffer or array
interfaces.
Example
A 2-dimensional array of size 2 x 3, composed of 4-byte integer elements:
>>> y = x[:,1]
>>> y
array([2, 5])
>>> y[0] = 9 # this also changes the corresponding element in x
>>> y
array([9, 5])
>>> x
array([[1, 9, 3],
[4, 5, 6]])
New arrays can be constructed using the routines detailed in Array creation routines, and also by using the low-level
ndarray constructor:
ndarray An array object represents a multidimensional, homogeneous array of fixed-size items.
class ndarray()
An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type
object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory,
whether it is an integer, a floating point number, or something else, etc.)
Arrays should be constructed using array, zeros or empty (refer to the See Also section below). The parameters
given here refer to a low-level method (ndarray(...)) for instantiating an array.
For more information, refer to the numpy module and examine the the methods and attributes of an array.
Parameters
(for the __new__ method; see Notes below) :
shape : tuple of ints
Shape of created array.
dtype : data-type, optional
array
Construct an array.
zeros
Create an array, each element of which is zero.
empty
Create an array, but leave its allocated memory unchanged (i.e., it contains garbage).
dtype
Create a data-type.
Notes
There are two modes of creating an array using __new__:
1.If buffer is None, then only shape, dtype, and order are used.
2.If buffer is an object exposing the buffer interface, then all keywords are interpreted.
No __init__ method is needed because the array is fully initialized after the __new__ method.
Examples
These examples illustrate the low-level ndarray constructor. Refer to the See Also section above for easier ways
of constructing an ndarray.
First mode, buffer is None:
Second mode:
Attributes
T Same as self.transpose(), except that self is returned if self.ndim < 2.
data Python buffer object pointing to the start of the arrays data.
dtype Data-type of the arrays elements.
flags Information about the memory layout of the array.
flat A 1-D iterator over the array.
imag The imaginary part of the array.
real The real part of the array.
size Number of elements in the array.
itemsize Length of one array element in bytes.
nbytes Total bytes consumed by the elements of the array.
ndim Number of array dimensions.
shape Tuple of array dimensions.
strides Tuple of bytes to step in each dimension when traversing an array.
ctypes An object to simplify the interaction of the array with the ctypes module.
base Base object if memory is from some other object.
T
Same as self.transpose(), except that self is returned if self.ndim < 2.
Examples
>>> x = np.array([[1.,2.],[3.,4.]])
>>> x
array([[ 1., 2.],
[ 3., 4.]])
>>> x.T
array([[ 1., 3.],
[ 2., 4.]])
>>> x = np.array([1.,2.,3.,4.])
>>> x
array([ 1., 2., 3., 4.])
>>> x.T
array([ 1., 2., 3., 4.])
data
Python buffer object pointing to the start of the arrays data.
dtype
Data-type of the arrays elements.
Parameters
None :
Returns
d : numpy dtype object
See Also:
numpy.dtype
Examples
>>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype(int32)
>>> type(x.dtype)
<type numpy.dtype>
flags
Information about the memory layout of the array.
Notes
The flags object can be accessed dictionary-like (as in a.flags[WRITEABLE]), or by using lower-
cased attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary
access.
Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct
assignment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
UPDATEIFCOPY can only be set False.
ALIGNED can only be set True if the data is truly aligned.
WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the
memory exposes a writeable buffer interface or is a string.
Attributes
flat
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Pythons built-in
iterator object.
See Also:
flatten
Return a copy of the array collapsed into one dimension.
flatiter
Examples
An assignment example:
>>> x.flat = 3; x
array([[3, 3, 3],
[3, 3, 3]])
>>> x.flat[[1,4]] = 1; x
array([[3, 1, 3],
[3, 1, 3]])
imag
The imaginary part of the array.
Examples
real
The real part of the array.
See Also:
numpy.real
equivalent function
Examples
size
Number of elements in the array.
Equivalent to np.prod(a.shape), i.e., the product of the arrays dimensions.
Examples
itemsize
Length of one array element in bytes.
Examples
>>> x.itemsize
16
nbytes
Total bytes consumed by the elements of the array.
Notes
Does not include memory consumed by non-element attributes of the array object.
Examples
ndim
Number of array dimensions.
Examples
shape
Tuple of array dimensions.
Notes
May be used to reshape the array, as long as this would not require a change in the total number of
elements
Examples
strides
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:
A more detailed explanation of strides can be found in the ndarray.rst file in the NumPy reference guide.
See Also:
numpy.lib.stride_tricks.as_strided
Notes
Imagine an array of 32-bit integers (each 4 bytes):
x = np.array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]], dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory).
The strides of an array tell us how many bytes we have to skip in memory to move to the next position
along a certain axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20
bytes (5 values) to get to the same position in the next row. As such, the strides for the array x will be
(20, 4).
Examples
ctypes
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the
ctypes module. The returned object has, among others, data, shape, and strides attributes (see Notes
below) which themselves return ctypes objects that can be used as arguments to a shared library.
Parameters
None :
Returns
c : Python object
Possessing attributes data, shape, strides, etc.
See Also:
numpy.ctypeslib
Notes
Below are the public attributes of this object which were documented in Guide to NumPy (we have
omitted undocumented public attributes, as well as documented private attributes):
data: A pointer to the memory area of the array as a Python integer. This memory area may contain
data that is not aligned, or not in correct byte-order. The memory area may not even be writeable.
The array flags and data-type of this array should be respected when passing this attribute to arbitrary
C-code to avoid trouble that can include Python crashing. User Beware! The value of this attribute is
exactly the same as self._array_interface_[data][0].
shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer
corresponding to dtype(p) on this platform. This base-type could be c_int, c_long, or c_longlong
depending on the platform. The c_intp type is defined accordingly in numpy.ctypeslib. The ctypes
array contains the shape of the underlying array.
strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for
the shape attribute. This ctypes array contains the strides information from the underlying array.
This strides information is important for showing how many bytes must be jumped to get to the next
element in the array.
data_as(obj): Return the data pointer cast to a particular c-types object. For example, calling
self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data
as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
shape_as(obj): Return the shape tuple as an array of some other c-types type. For example:
self.shape_as(ctypes.c_short).
strides_as(obj): Return the strides tuple as an array of some other c-types type. For example:
self.strides_as(ctypes.c_longlong).
Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For
example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that
is invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid
this problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to
the array until ct is deleted or re-assigned.
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful,
but ctypes objects are not returned and errors may be raised instead. In particular, the object will still have
the as parameter attribute which will return an integer equal to the data attribute.
Examples
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_long))
<ctypes.LP_c_long object at 0x01F01300>
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_long)).contents
c_long(0)
>>> x.ctypes.data_as(ctypes.POINTER(ctypes.c_longlong)).contents
c_longlong(4294967296L)
>>> x.ctypes.shape
<numpy.core._internal.c_long_Array_2 object at 0x01FFD580>
>>> x.ctypes.shape_as(ctypes.c_long)
<numpy.core._internal.c_long_Array_2 object at 0x01FCE620>
>>> x.ctypes.strides
<numpy.core._internal.c_long_Array_2 object at 0x01FCE620>
>>> x.ctypes.strides_as(ctypes.c_longlong)
<numpy.core._internal.c_longlong_Array_2 object at 0x01F01300>
base
Base object if memory is from some other object.
Examples
The base of an array that owns its memory is None:
>>> x = np.array([1,2,3,4])
>>> x.base is None
True
>>> y = x[2:]
>>> y.base is x
True
Methods
all(axis=None, out=None)
Returns True if all elements evaluate to True.
Refer to numpy.all for full documentation.
See Also:
numpy.all
equivalent function
any(axis=None, out=None)
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
See Also:
numpy.any
equivalent function
argmax(axis=None, out=None)
Return indices of the maximum values along the given axis.
Refer to numpy.argmax for full documentation.
See Also:
numpy.argmax
equivalent function
argmin(axis=None, out=None)
Return indices of the minimum values along the given axis of a.
Refer to numpy.argmin for detailed documentation.
See Also:
numpy.argmin
equivalent function
numpy.argsort
equivalent function
astype(t)
Copy of the array, cast to a specified type.
Parameters
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
>>> x.astype(int)
array([1, 2, 2])
byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, option-
ally swapped in-place.
Parameters
inplace: bool, optional :
If True, swap bytes in-place, default is False.
Returns
out: ndarray :
Examples
numpy.choose
equivalent function
numpy.clip
equivalent function
numpy.compress
equivalent function
conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
numpy.cumprod
equivalent function
numpy.cumsum
equivalent function
numpy.diagonal
equivalent function
dot()
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an
array.
Parameters
None :
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
getfield(dtype, offset)
Returns a field of the given array as a certain type.
A field is a view of the array data with each itemsize determined by the given type and the offset into the
current array, i.e. from offset * dtype.itemsize to (offset+1) * dtype.itemsize.
Parameters
dtype : str
String denoting the data type of the field.
offset : int
Number of dtype.itemsizes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
>>> x.dtype
dtype(complex128)
>>> x.getfield(complex128, 0) # == x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
If the argument dtype is the same as x.dtype, then offset != 0 raises a ValueError:
>>> x.getfield(complex128, 1)
Traceback (most recent call last):
>>> x.getfield(float64, 0)
array([[ 1., 0.],
[ 0., 1.]])
>>> x.getfield(float64, 1)
array([[ 1.77658241e-307, 0.00000000e+000],
[ 0.00000000e+000, 1.77658241e-307]])
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which ele-
ment to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument
is interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is
no available Python scalar that would not lose information. Void arrays return a buffer object for item(),
unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This
can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array
using Pythons optimized math.
Examples
itemset()
max(axis=None, out=None)
Return the maximum along a given axis.
Refer to numpy.amax for full documentation.
See Also:
numpy.amax
equivalent function
numpy.mean
equivalent function
min(axis=None, out=None)
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See Also:
numpy.amin
equivalent function
newbyteorder(new_order=S)
Return the array with the same data viewed with a different byte order.
Equivalent to:
arr.view(arr.dtype.newbytorder(new_order))
Changes are also made in all fields and sub-arrays of the array data type.
Parameters
new_order : string, optional
Byte order to force; a value from the byte order specifications above. new_order codes
can be any of:
The default value (S) results in swapping the current byte order. The code does a
case-insensitive check on the first letter of new_order for the alternatives above. For
example, any of B or b or biggish are valid to specify big-endian.
Returns
new_arr : array
New array object with the dtype reflecting given change to the byte order.
nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
numpy.prod
equivalent function
ptp(axis=None, out=None)
Peak to peak (maximum - minimum) value along a given axis.
Refer to numpy.ptp for full documentation.
See Also:
numpy.ptp
equivalent function
numpy.put
equivalent function
ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See Also:
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
reshape(shape, order=C)
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See Also:
numpy.reshape
equivalent function
resize(new_shape, refcheck=True)
Change shape and size of array in-place.
Parameters
new_shape : tuple of ints, or n ints
Shape of resized array.
refcheck : bool, optional
If False, reference count will not be checked. Default is True.
Returns
None :
Raises
ValueError :
If a does not own its own data or references or views to it exist, and the data memory
must be changed.
SystemError :
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See Also:
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another
Python object and then reallocate the memory. However, reference counts can increase in other ways so if
you are sure that you have not shared the memory for this array with another Python object, then you may
safely set refcheck to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and re-
shaped:
Enlarging an array: as above, but missing entries are filled with zeros:
>>> c = a
>>> a.resize((1, 1))
...
ValueError: cannot resize an array that has been referenced ...
round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to numpy.around for full documentation.
See Also:
numpy.around
equivalent function
searchsorted(v, side=left)
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See Also:
numpy.searchsorted
equivalent function
Examples
>>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> x
array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323],
[ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323],
[ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There
are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITE-
ABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the com-
piler);
UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is
deallocated, the base array will be updated with the contents of this array.
All flags can be accessed using their first (upper case) letter as well as the full name.
Examples
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True
When a is an array with fields defined, this argument specifies which fields to compare
first, second, etc. Not all fields need be specified.
See Also:
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
numpy.std
equivalent function
numpy.sum
equivalent function
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
numpy.take
equivalent function
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision
is lost, so this method is not a good choice for files intended to archive data or transport data between
machines with different endianness. Some of these problems can be overcome by outputting the data as
text files, at the expense of speed and file size.
tolist()
Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible
Python type.
Parameters
none :
Returns
y : list
The possibly nested list of array elements.
Notes
The array may be recreated, a = np.array(a.tolist()).
Examples
tostring(order=C)
Construct a Python string containing the raw data bytes in the array.
Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced
in either C or Fortran, or Any order (the default is C-order). Any order means C-order unless the
F_CONTIGUOUS flag in the array is set, in which case it means Fortran order.
Parameters
order : {C, F, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original
array.
Returns
s : str
A Python string exhibiting a copy of as raw data.
Examples
numpy.trace
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D ar-
ray into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes
are given, their order indicates how the axes are permuted (see Examples). If axes are not provided
and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape
= (i[n-1], i[n-2], ... i[1], i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s
j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
numpy.var
equivalent function
view(dtype=None, type=None)
New view of array with the same data.
Parameters
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
type : python type
Type of the returned view, e.g. ndarray or matrix.
Notes
a.view() is used two different ways.
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the arrays memory with a different
dtype. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass), or a.view(type=ndarray_subclass), just returns an instance of ndarray_subclass
that looks at the same array (same shape, dtype, etc.). This does not cause a reinterpretation of the memory.
Examples
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
Arrays can be indexed using an extended Python slicing syntax, array[selection]. Similar syntax is also used
for accessing fields in a record array.
See Also:
Array Indexing.
An instance of class ndarray consists of a contiguous one-dimensional segment of computer memory (owned by
the array, or by some other object), combined with an indexing scheme that maps N integers into the location of an
item in the block. The ranges in which the indices can vary is specified by the shape of the array. How many
bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.
A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of
an N-dimensional array in a 1-dimensional block. Numpy is flexible, and ndarray objects can accommodate any
strided indexing scheme. In a strided scheme, the N-dimensional index (n0 , n1 , ..., nN 1 ) corresponds to the offset
(in bytes):
N
X 1
noffset = sk nk
k=0
from the beginning of the memory block associated with the array. Here, sk are integers which specify the strides
of the array. The column-major order (used, for example, in the Fortran language and in Matlab) and row-major order
(used in C) schemes are just specific kinds of strided scheme, and correspond to the strides:
k1
Y N
Y 1
scolumn
k = dj , srow
k = dj .
j=0 j=k+1
Array attributes reflect information that is intrinsic to the array itself. Generally, accessing an array through its at-
tributes allows you to get and sometimes set intrinsic properties of the array without creating a new array. The exposed
attributes are the core parts of an array and only some of them can be reset meaningfully without creating a new array.
Information on each attribute is given below.
Memory layout
The following attributes contain information about the memory layout of the array:
ndarray.flags Information about the memory layout of the array.
ndarray.shape Tuple of array dimensions.
ndarray.strides Tuple of bytes to step in each dimension when traversing an array.
ndarray.ndim Number of array dimensions.
ndarray.data Python buffer object pointing to the start of the arrays data.
ndarray.size Number of elements in the array.
ndarray.itemsize Length of one array element in bytes.
ndarray.nbytes Total bytes consumed by the elements of the array.
ndarray.base Base object if memory is from some other object.
flags
Information about the memory layout of the array.
Notes
The flags object can be accessed dictionary-like (as in a.flags[WRITEABLE]), or by using lowercased
attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.
Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assign-
ment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
UPDATEIFCOPY can only be set False.
ALIGNED can only be set True if the data is truly aligned.
WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the memory
exposes a writeable buffer interface or is a string.
Attributes
shape
Tuple of array dimensions.
Notes
May be used to reshape the array, as long as this would not require a change in the total number of elements
Examples
strides
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:
A more detailed explanation of strides can be found in the ndarray.rst file in the NumPy reference guide.
See Also:
numpy.lib.stride_tricks.as_strided
Notes
Imagine an array of 32-bit integers (each 4 bytes):
x = np.array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]], dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The
strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain
axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get
to the same position in the next row. As such, the strides for the array x will be (20, 4).
Examples
ndim
Number of array dimensions.
Examples
data
Python buffer object pointing to the start of the arrays data.
size
Number of elements in the array.
Equivalent to np.prod(a.shape), i.e., the product of the arrays dimensions.
Examples
itemsize
Length of one array element in bytes.
Examples
nbytes
Total bytes consumed by the elements of the array.
Notes
Does not include memory consumed by non-element attributes of the array object.
Examples
base
Base object if memory is from some other object.
Examples
The base of an array that owns its memory is None:
>>> x = np.array([1,2,3,4])
>>> x.base is None
True
>>> y = x[2:]
>>> y.base is x
True
Data type
See Also:
Data type objects
The data type object associated with the array can be found in the dtype attribute:
ndarray.dtype Data-type of the arrays elements.
dtype
Data-type of the arrays elements.
Parameters
None :
Returns
d : numpy dtype object
See Also:
numpy.dtype
Examples
>>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype(int32)
>>> type(x.dtype)
<type numpy.dtype>
Other attributes
Examples
>>> x = np.array([[1.,2.],[3.,4.]])
>>> x
array([[ 1., 2.],
[ 3., 4.]])
>>> x.T
array([[ 1., 3.],
[ 2., 4.]])
>>> x = np.array([1.,2.,3.,4.])
>>> x
array([ 1., 2., 3., 4.])
>>> x.T
array([ 1., 2., 3., 4.])
real
The real part of the array.
See Also:
numpy.real
equivalent function
Examples
imag
The imaginary part of the array.
Examples
flat
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Pythons built-in iterator
object.
See Also:
flatten
Return a copy of the array collapsed into one dimension.
flatiter
Examples
An assignment example:
>>> x.flat = 3; x
array([[3, 3, 3],
[3, 3, 3]])
>>> x.flat[[1,4]] = 1; x
array([[3, 1, 3],
[3, 1, 3]])
ctypes
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes
module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which
themselves return ctypes objects that can be used as arguments to a shared library.
Parameters
None :
Returns
c : Python object
Possessing attributes data, shape, strides, etc.
See Also:
numpy.ctypeslib
Notes
Below are the public attributes of this object which were documented in Guide to NumPy (we have omitted
undocumented public attributes, as well as documented private attributes):
data: A pointer to the memory area of the array as a Python integer. This memory area may contain data
that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array
flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid
trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as
self._array_interface_[data][0].
shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corre-
sponding to dtype(p) on this platform. This base-type could be c_int, c_long, or c_longlong depending
on the platform. The c_intp type is defined accordingly in numpy.ctypeslib. The ctypes array contains the
shape of the underlying array.
strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the
shape attribute. This ctypes array contains the strides information from the underlying array. This strides
information is important for showing how many bytes must be jumped to get to the next element in the
array.
data_as(obj): Return the data pointer cast to a particular c-types object. For example, calling
self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as
a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
shape_as(obj): Return the shape tuple as an array of some other c-types type. For example:
self.shape_as(ctypes.c_short).
strides_as(obj): Return the strides tuple as an array of some other c-types type. For example:
self.strides_as(ctypes.c_longlong).
Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For
example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that is
invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this
problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array
until ct is deleted or re-assigned.
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but
ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as
parameter attribute which will return an integer equal to the data attribute.
Examples
Array interface
See Also:
The Array Interface.
__array_interface__ Python-side of the array interface
__array_struct__ C-side of the array interface
ndarray.ctypes An object to simplify the interaction of the array with the ctypes module.
ctypes
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes
module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which
themselves return ctypes objects that can be used as arguments to a shared library.
Parameters
None :
Returns
c : Python object
Possessing attributes data, shape, strides, etc.
See Also:
numpy.ctypeslib
Notes
Below are the public attributes of this object which were documented in Guide to NumPy (we have omitted
undocumented public attributes, as well as documented private attributes):
data: A pointer to the memory area of the array as a Python integer. This memory area may contain data
that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array
flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid
trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as
self._array_interface_[data][0].
shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corre-
sponding to dtype(p) on this platform. This base-type could be c_int, c_long, or c_longlong depending
on the platform. The c_intp type is defined accordingly in numpy.ctypeslib. The ctypes array contains the
shape of the underlying array.
strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the
shape attribute. This ctypes array contains the strides information from the underlying array. This strides
information is important for showing how many bytes must be jumped to get to the next element in the
array.
data_as(obj): Return the data pointer cast to a particular c-types object. For example, calling
self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as
a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
shape_as(obj): Return the shape tuple as an array of some other c-types type. For example:
self.shape_as(ctypes.c_short).
strides_as(obj): Return the strides tuple as an array of some other c-types type. For example:
self.strides_as(ctypes.c_longlong).
Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For
example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that is
invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this
problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array
until ct is deleted or re-assigned.
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but
ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as
parameter attribute which will return an integer equal to the data attribute.
Examples
An ndarray object has many methods which operate on or with the array in some fashion, typically returning an
array result. These methods are briefly explained below. (Each methods docstring has a more complete description.)
For the following methods there are also corresponding functions in numpy: all, any, argmax, argmin,
argsort, choose, clip, compress, copy, cumprod, cumsum, diagonal, imag, max, mean, min,
nonzero, prod, ptp, put, ravel, real, repeat, reshape, round, searchsorted, sort, squeeze,
std, sum, swapaxes, take, trace, transpose, var.
Array conversion
ndarray.item(*args) Copy an element of an array to a standard Python scalar and return it.
ndarray.tolist() Return the array as a (possibly nested) list.
ndarray.itemset
ndarray.tostring([order]) Construct a Python string containing the raw data bytes in the array.
ndarray.tofile(fid[, sep, Write array to a file as text or binary (default).
format])
ndarray.dump(file) Dump a pickle of the array to the specified file.
ndarray.dumps() Returns the pickle of the array as a string.
ndarray.astype(t) Copy of the array, cast to a specified type.
ndarray.byteswap(inplace) Swap the bytes of the array elements
ndarray.copy([order]) Return a copy of the array.
ndarray.view([dtype, type]) New view of array with the same data.
ndarray.getfield(dtype, offset) Returns a field of the given array as a certain type.
ndarray.setflags([write, align, Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY,
uic]) respectively.
ndarray.fill(value) Fill the array with a scalar value.
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which element
to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument is
interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no
available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless
fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can
be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using
Pythons optimized math.
Examples
5
>>> x.item((0, 1))
1
>>> x.item((2, 2))
3
tolist()
Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible
Python type.
Parameters
none :
Returns
y : list
The possibly nested list of array elements.
Notes
The array may be recreated, a = np.array(a.tolist()).
Examples
itemset()
tostring(order=C)
Construct a Python string containing the raw data bytes in the array.
Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced
in either C or Fortran, or Any order (the default is C-order). Any order means C-order unless the
F_CONTIGUOUS flag in the array is set, in which case it means Fortran order.
Parameters
order : {C, F, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original
array.
Returns
s : str
A Python string exhibiting a copy of as raw data.
Examples
\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00
>>> x.tostring(C) == x.tostring()
True
>>> x.tostring(F)
\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision is lost,
so this method is not a good choice for files intended to archive data or transport data between machines with
different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense
of speed and file size.
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an array.
Parameters
None :
astype(t)
Copy of the array, cast to a specified type.
Parameters
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
>>> x.astype(int)
array([1, 2, 2])
byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally
swapped in-place.
Parameters
inplace: bool, optional :
If True, swap bytes in-place, default is False.
Returns
out: ndarray :
The byteswapped array. If inplace is True, this is a view to self.
Examples
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
view(dtype=None, type=None)
New view of array with the same data.
Parameters
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
type : python type
Type of the returned view, e.g. ndarray or matrix.
Notes
a.view() is used two different ways.
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the arrays memory with a different
dtype. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass), or a.view(type=ndarray_subclass), just returns an instance of ndarray_subclass that
looks at the same array (same shape, dtype, etc.). This does not cause a reinterpretation of the memory.
Examples
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
getfield(dtype, offset)
Returns a field of the given array as a certain type.
A field is a view of the array data with each itemsize determined by the given type and the offset into the current
array, i.e. from offset * dtype.itemsize to (offset+1) * dtype.itemsize.
Parameters
dtype : str
String denoting the data type of the field.
offset : int
Number of dtype.itemsizes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
>>> x.dtype
dtype(complex128)
>>> x.getfield(complex128, 0) # == x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
If the argument dtype is the same as x.dtype, then offset != 0 raises a ValueError:
>>> x.getfield(complex128, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Need 0 <= offset <= 0 for requested type but received offset = 1
>>> x.getfield(float64, 0)
array([[ 1., 0.],
[ 0., 1.]])
>>> x.getfield(float64, 1)
array([[ 1.77658241e-307, 0.00000000e+000],
[ 0.00000000e+000, 1.77658241e-307]])
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There are
6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITEABLE, and
ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler);
UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is deallo-
cated, the base array will be updated with the contents of this array.
All flags can be accessed using their first (upper case) letter as well as the full name.
Examples
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
Shape manipulation
For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted
as an n-tuple.
ndarray.reshape(shape[, order]) Returns an array containing the same data with a new shape.
ndarray.resize(new_shape[, refcheck]) Change shape and size of array in-place.
ndarray.transpose(*axes) Returns a view of the array with axes transposed.
ndarray.swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged.
ndarray.flatten([order]) Return a copy of the array collapsed into one dimension.
ndarray.ravel() Return a flattened array.
ndarray.squeeze() Remove single-dimensional entries from the shape of a.
reshape(shape, order=C)
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See Also:
numpy.reshape
equivalent function
resize(new_shape, refcheck=True)
Change shape and size of array in-place.
Parameters
new_shape : tuple of ints, or n ints
Shape of resized array.
refcheck : bool, optional
If False, reference count will not be checked. Default is True.
Returns
None :
Raises
ValueError :
If a does not own its own data or references or views to it exist, and the data memory
must be changed.
SystemError :
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See Also:
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python
object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure
that you have not shared the memory for this array with another Python object, then you may safely set refcheck
to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and reshaped:
Enlarging an array: as above, but missing entries are filled with zeros:
>>> c = a
>>> a.resize((1, 1))
...
ValueError: cannot resize an array that has been referenced ...
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a ma-
trix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order in-
dicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1],
... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1],
i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s j-th
axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
[2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
[2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
[2, 4]])
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is
C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See Also:
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
For array methods that take an axis keyword, it defaults to None. If axis is None, then the array is treated as a 1-D
array. Any other value for axis represents the dimension along which the operation should proceed.
ndarray.take(indices[, axis, out, Return an array formed from the elements of a at the given indices.
mode])
ndarray.put(indices, values[, mode]) Set a.flat[n] = values[n] for all n in indices.
ndarray.repeat(repeats[, axis]) Repeat elements of an array.
ndarray.choose(choices[, out, Use an index array to construct a new array from a set of choices.
mode])
ndarray.sort([axis, kind, order]) Sort an array, in-place.
ndarray.argsort([axis, kind, order]) Returns the indices that would sort this array.
ndarray.searchsorted(v[, side]) Find indices where elements of v should be inserted in a to maintain
order.
ndarray.nonzero() Return the indices of the elements that are non-zero.
ndarray.compress(condition[, axis, Return selected slices of this array along given axis.
out])
ndarray.diagonal([offset, axis1, Return specified diagonals.
axis2])
take(indices, axis=None, out=None, mode=raise)
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See Also:
numpy.take
equivalent function
numpy.put
equivalent function
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
numpy.choose
equivalent function
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
numpy.argsort
equivalent function
searchsorted(v, side=left)
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See Also:
numpy.searchsorted
equivalent function
nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
numpy.compress
equivalent function
numpy.diagonal
equivalent function
Calculation
>>> x
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
>>> x.sum(axis=0)
array([[27, 30, 33],
[36, 39, 42],
[45, 48, 51]])
>>> # for sum, axis is the first keyword, so we may omit it,
>>> # specifying only its value
>>> x.sum(0), x.sum(1), x.sum(2)
(array([[27, 30, 33],
[36, 39, 42],
[45, 48, 51]]),
array([[ 9, 12, 15],
[36, 39, 42],
[63, 66, 69]]),
array([[ 3, 12, 21],
[30, 39, 48],
[57, 66, 75]]))
The parameter dtype specifies the data type over which a reduction operation (like summing) should take place. The
default reduce data type is the same as the data type of self. To avoid overflow, it can be useful to perform the reduction
using a larger data type.
For several methods, an optional out argument can also be provided and the result will be placed into the output array
given. The out argument must be an ndarray and have the same number of elements. It can have a different data
type in which case casting will be performed.
ndarray.argmax([axis, out]) Return indices of the maximum values along the given axis.
ndarray.min([axis, out]) Return the minimum along a given axis.
ndarray.argmin([axis, out]) Return indices of the minimum values along the given axis of
a.
ndarray.ptp([axis, out]) Peak to peak (maximum - minimum) value along a given axis.
ndarray.clip(a_min, a_max[, out]) Return an array whose values are limited to [a_min,
a_max].
ndarray.conj() Complex-conjugate all elements.
ndarray.round([decimals, out]) Return an array rounded a to the given number of decimals.
ndarray.trace([offset, axis1, axis2, dtype, Return the sum along diagonals of the array.
out])
ndarray.sum([axis, dtype, out]) Return the sum of the array elements over the given axis.
ndarray.cumsum([axis, dtype, out]) Return the cumulative sum of the elements along the given
axis.
ndarray.mean([axis, dtype, out]) Returns the average of the array elements along given axis.
ndarray.var([axis, dtype, out, ddof]) Returns the variance of the array elements, along given axis.
ndarray.std([axis, dtype, out, ddof]) Returns the standard deviation of the array elements along
given axis.
ndarray.prod([axis, dtype, out]) Return the product of the array elements over the given axis
ndarray.cumprod([axis, dtype, out]) Return the cumulative product of the elements along the given
axis.
ndarray.all([axis, out]) Returns True if all elements evaluate to True.
ndarray.any([axis, out]) Returns True if any of the elements of a evaluate to True.
argmax(axis=None, out=None)
Return indices of the maximum values along the given axis.
Refer to numpy.argmax for full documentation.
See Also:
numpy.argmax
equivalent function
min(axis=None, out=None)
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See Also:
numpy.amin
equivalent function
argmin(axis=None, out=None)
Return indices of the minimum values along the given axis of a.
Refer to numpy.argmin for detailed documentation.
See Also:
numpy.argmin
equivalent function
ptp(axis=None, out=None)
Peak to peak (maximum - minimum) value along a given axis.
Refer to numpy.ptp for full documentation.
See Also:
numpy.ptp
equivalent function
numpy.clip
equivalent function
conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to numpy.around for full documentation.
See Also:
numpy.around
equivalent function
numpy.trace
equivalent function
numpy.sum
equivalent function
See Also:
numpy.cumsum
equivalent function
numpy.mean
equivalent function
numpy.var
equivalent function
numpy.std
equivalent function
numpy.prod
equivalent function
numpy.cumprod
equivalent function
all(axis=None, out=None)
Returns True if all elements evaluate to True.
Refer to numpy.all for full documentation.
See Also:
numpy.all
equivalent function
any(axis=None, out=None)
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
See Also:
numpy.any
equivalent function
Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield
ndarray objects as results.
Each of the arithmetic operations (+, -, *, /, //, %, divmod(), ** or pow(), <<, >>, &, ^, |, ~) and the
comparisons (==, <, >, <=, >=, !=) is equivalent to the corresponding universal function (or ufunc for short) in
Numpy. For more information, see the section on Universal Functions.
Comparison operators:
ndarray.__lt__ x.__lt__(y) <==> x<y
ndarray.__le__ x.__le__(y) <==> x<=y
ndarray.__gt__ x.__gt__(y) <==> x>y
ndarray.__ge__ x.__ge__(y) <==> x>=y
ndarray.__eq__ x.__eq__(y) <==> x==y
ndarray.__ne__ x.__ne__(y) <==> x!=y
__lt__()
x.__lt__(y) <==> x<y
__le__()
x.__le__(y) <==> x<=y
__gt__()
x.__gt__(y) <==> x>y
__ge__()
x.__ge__(y) <==> x>=y
__eq__()
x.__eq__(y) <==> x==y
__ne__()
x.__ne__(y) <==> x!=y
Truth value of an array (bool):
ndarray.__nonzero__ x.__nonzero__() <==> x != 0
__nonzero__()
x.__nonzero__() <==> x != 0
Note: Truth-value testing of an array invokes ndarray.__nonzero__, which raises an error if the number of
elements in the the array is larger than 1, because the truth value of such arrays is ambiguous. Use .any() and
.all() instead to be clear about what is meant in such cases. (If the number of elements is 0, the array evaluates to
False.)
Unary operations:
ndarray.__neg__ x.__neg__() <==> -x
ndarray.__pos__ x.__pos__() <==> +x
ndarray.__abs__(x)
ndarray.__invert__ x.__invert__() <==> ~x
__neg__()
x.__neg__() <==> -x
__pos__()
x.__pos__() <==> +x
__abs__() <==> abs(x)
__invert__()
x.__invert__() <==> ~x
Arithmetic:
ndarray.__add__ x.__add__(y) <==> x+y
ndarray.__sub__ x.__sub__(y) <==> x-y
ndarray.__mul__ x.__mul__(y) <==> x*y
ndarray.__div__ x.__div__(y) <==> x/y
ndarray.__truediv__ x.__truediv__(y) <==> x/y
ndarray.__floordiv__ x.__floordiv__(y) <==> x//y
ndarray.__mod__ x.__mod__(y) <==> x%y
ndarray.__divmod__(x, y)
ndarray.__pow__(x)
ndarray.__lshift__ x.__lshift__(y) <==> x<<y
ndarray.__rshift__ x.__rshift__(y) <==> x>>y
ndarray.__and__ x.__and__(y) <==> x&y
ndarray.__or__ x.__or__(y) <==> x|y
ndarray.__xor__ x.__xor__(y) <==> x^y
__add__()
x.__add__(y) <==> x+y
__sub__()
x.__sub__(y) <==> x-y
__mul__()
x.__mul__(y) <==> x*y
__div__()
x.__div__(y) <==> x/y
__truediv__()
x.__truediv__(y) <==> x/y
__floordiv__()
x.__floordiv__(y) <==> x//y
__mod__()
x.__mod__(y) <==> x%y
__divmod__(y) <==> divmod(x, y)
__lshift__()
x.__lshift__(y) <==> x<<y
__rshift__()
x.__rshift__(y) <==> x>>y
__and__()
x.__and__(y) <==> x&y
__or__()
x.__or__(y) <==> x|y
__xor__()
x.__xor__(y) <==> x^y
Note:
Any third argument to pow is silently ignored, as the underlying ufunc takes only two arguments.
The three division operators are all defined; div is active by default, truediv is active when __future__
division is in effect.
Because ndarray is a built-in type (written in C), the __r{op}__ special methods are not directly defined.
The functions called to implement many arithmetic special methods for arrays can be modified using
set_numeric_ops.
Arithmetic, in-place:
ndarray.__iadd__ x.__iadd__(y) <==> x+y
ndarray.__isub__ x.__isub__(y) <==> x-y
ndarray.__imul__ x.__imul__(y) <==> x*y
ndarray.__idiv__ x.__idiv__(y) <==> x/y
ndarray.__itruediv__ x.__itruediv__(y) <==> x/y
ndarray.__ifloordiv__ x.__ifloordiv__(y) <==> x//y
ndarray.__imod__ x.__imod__(y) <==> x%y
ndarray.__ipow__ x.__ipow__(y) <==> x**y
ndarray.__ilshift__ x.__ilshift__(y) <==> x<<y
ndarray.__irshift__ x.__irshift__(y) <==> x>>y
ndarray.__iand__ x.__iand__(y) <==> x&y
ndarray.__ior__ x.__ior__(y) <==> x|y
ndarray.__ixor__ x.__ixor__(y) <==> x^y
__iadd__()
x.__iadd__(y) <==> x+y
__isub__()
x.__isub__(y) <==> x-y
__imul__()
x.__imul__(y) <==> x*y
__idiv__()
x.__idiv__(y) <==> x/y
__itruediv__()
x.__itruediv__(y) <==> x/y
__ifloordiv__()
x.__ifloordiv__(y) <==> x//y
__imod__()
x.__imod__(y) <==> x%y
__ipow__()
x.__ipow__(y) <==> x**y
__ilshift__()
x.__ilshift__(y) <==> x<<y
__irshift__()
x.__irshift__(y) <==> x>>y
__iand__()
x.__iand__(y) <==> x&y
__ior__()
x.__ior__(y) <==> x|y
__ixor__()
x.__ixor__(y) <==> x^y
Warning: In place operations will perform the calculation using the precision decided by the data type of the
two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore,
for mixed precision calculations, A {op}= B can be different than A = A {op} B. For example, suppose
a = ones((3,3)). Then, a += 3j is different than a = a + 3j: while they both perform the same
computation, a += 3 casts the result to fit back in a, whereas a = a + 3j re-binds the name a to the result.
__getitem__()
x.__getitem__(y) <==> x[y]
__setitem__()
x.__setitem__(i, y) <==> x[i]=y
__getslice__()
x.__getslice__(i, j) <==> x[i:j]
Use of negative indices is not supported.
__setslice__()
x.__setslice__(i, j, y) <==> x[i:j]=y
Use of negative indices is not supported.
__contains__()
x.__contains__(y) <==> y in x
Conversion; the operations complex, int, long, float, oct, and hex. They work only on arrays that have one
element in them and return the appropriate scalar.
ndarray.__int__(x)
ndarray.__long__(x)
ndarray.__float__(x)
ndarray.__oct__(x)
ndarray.__hex__(x)
__int__() <==> int(x)
String representations:
ndarray.__str__(x)
ndarray.__repr__(x)
__str__() <==> str(x)
1.2 Scalars
Python defines only one type of a particular data class (there is only one integer type, one floating-point type, etc.).
This can be convenient in applications that dont need to be concerned with all the ways data can be represented in a
computer. For scientific computing, however, more control is often needed.
In NumPy, there are 21 new fundamental Python types to describe different types of scalars. These type descriptors
are mostly based on the types available in the C language that CPython is written in, with several additional types
compatible with Pythons types.
Array scalars have the same attributes and methods as ndarrays. 1 This allows one to treat items of an array partly
on the same footing as arrays, smoothing out rough edges that result when mixing scalar and array operations.
Array scalars live in a hierarchy (see the Figure below) of data types. They can be detected using the hierarchy:
For example, isinstance(val, np.generic) will return True if val is an array scalar object. Alternatively,
what kind of array scalar is present can be determined using other members of the data type hierarchy. Thus, for
example isinstance(val, np.complexfloating) will return True if val is a complex valued type, while
isinstance(val, np.flexible) will return true if val is one of the flexible itemsize array types (string,
unicode, void).
The built-in scalar types are shown below. Along with their (mostly) C-derived names, the integer, float, and complex
data-types are also available using a bit-width convention so that an array of the right size can always be ensured (e.g.
1 However, array scalars are immutable, so none of the array scalar attributes are settable.
Figure 1.2: Figure: Hierarchy of type objects representing the array data types. Not shown are the two integer types
intp and uintp which just point to the integer type that holds a pointer for the platform. All the number types can
be obtained using bit-width names as well.
1.2. Scalars 65
NumPy Reference, Release 2.0.0.dev8464
int8, float64, complex128). Two aliases (intp and uintp) pointing to the integer type that is sufficiently
large to hold a C pointer are also provided. The C-like names are associated with character codes, which are shown in
the table. Use of the character codes, however, is discouraged.
Five of the scalar types are essentially equivalent to fundamental Python types and therefore inherit from them as well
as from the generic array scalar type:
Array scalar type Related Python type
int_ IntType
float_ FloatType
complex_ ComplexType
str_ StringType
unicode_ UnicodeType
The bool_ data type is very similar to the Python BooleanType but does not inherit from it because Pythons
BooleanType does not allow itself to be inherited from, and on the C-level the size of the actual bool data is not the
same as a Python Boolean scalar.
Warning: The bool_ type is not a subclass of the int_ type (the bool_ is not even a number type). This is
different than Pythons default implementation of bool as a sub-class of int.
Floating-point numbers:
single compatible: C float f
double compatible: C double
float_ compatible: Python float d
longfloat compatible: C long float g
float32 32 bits
float64 64 bits
float96 96 bits, platform?
float128 128 bits, platform?
Complex floating-point numbers:
csingle F
complex_ compatible: Python complex D
clongfloat G
complex64 two 32-bit floats
complex128 two 64-bit floats
complex192 two 96-bit floats, platform?
complex256 two 128-bit floats, platform?
Any Python object:
object_ any Python object O
Note: The data actually stored in object arrays (i.e., arrays having dtype object_) are references to Python objects,
not the objects themselves. Hence, object arrays behave more like usual Python lists, in the sense that their contents
need not be of the same Python type.
The object type is also special because an array containing object_ items does not return an object_ object on
item access, but instead returns the actual object that the array item refers to.
The following data types are flexible. They have no predefined size: the data they describe can be of different length
in different arrays. (In the character codes # is an integer denoting how many elements the data type consists of.)
str_ compatible: Python str S#
unicode_ compatible: Python unicode U#
void V#
Warning: Numeric Compatibility: If you used old typecode characters in your Numeric code (which was never
recommended), you will need to change some of them to the new characters. In particular, the needed changes
are c -> S1, b -> B, 1 -> b, s -> h, w -> H, and u -> I. These changes make the type character
convention more consistent with other Python modules such as the struct module.
1.2.2 Attributes
The array scalar objects have an array priority of NPY_SCALAR_PRIORITY (-1,000,000.0). They also do
not (yet) have a ctypes attribute. Otherwise, they share the same attributes as arrays:
1.2. Scalars 67
NumPy Reference, Release 2.0.0.dev8464
__array_priority__
Array priority.
__array_wrap__()
sc.__array_wrap__(obj) return scalar from array
1.2.3 Indexing
See Also:
Indexing, Data type objects (dtype)
Array scalars can be indexed like 0-dimensional arrays: if x is an array scalar,
x[()] returns a 0-dimensional ndarray
x[field-name] returns the array scalar in the field field-name. (x can have fields, for example, when it
corresponds to a record data type.)
1.2.4 Methods
Array scalars have exactly the same methods as arrays. The default behavior of these methods is to internally convert
the scalar to an equivalent 0-dimensional array and to call the corresponding array method. In addition, math operations
on array scalars are defined so that the same hardware flags are set and used to interpret the results as for ufunc, so that
the error state used for ufuncs also carries over to the math on array scalars.
The exceptions to the above rules are given below:
generic Base class for numpy scalar types.
generic.__array__ sc.__array__(|type) return 0-dim array
generic.__array_wrap__ sc.__array_wrap__(obj) return scalar from array
generic.__squeeze__
generic.byteswap Not implemented (virtual attribute)
generic.__reduce__
generic.__setstate__
generic.setflags Not implemented (virtual attribute)
class generic()
Base class for numpy scalar types.
Class from which most (all?) numpy scalar types are derived. For consistency, exposes the same API as ndarray,
despite many consequent attributes being either get-only, or completely irrelevant. This is the class from which
it is strongly suggested users should derive custom scalar types.
Methods
1.2. Scalars 69
NumPy Reference, Release 2.0.0.dev8464
all()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
any()
1.2. Scalars 71
NumPy Reference, Release 2.0.0.dev8464
The
clip()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
compress()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
conj()
conjugate()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
copy()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
cumprod()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
cumsum()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
diagonal()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
dump()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
dumps()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
fill()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
flatten()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
getfield()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
item()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
1.2. Scalars 73
NumPy Reference, Release 2.0.0.dev8464
The
itemset()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
max()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
mean()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
min()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
newbyteorder(new_order=S)
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
The new_order code can be any from the following:
{<, L} - little endian
{>, B} - big endian
{=, N} - native order
S - swap dtype from current to opposite endian
{|, I} - ignore (no change to byte order)
Parameters
new_order : str, optional
Byte order to force; a value from the byte order specifications above. The default value
(S) results in swapping the current byte order. The code does a case-insensitive check
on the first letter of new_order for the alternatives above. For example, any of B or b
or biggish are valid to specify big-endian.
Returns
new_dtype : dtype
New dtype object with the given change to the byte order.
nonzero()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
prod()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
ptp()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
put()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
ravel()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
repeat()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
1.2. Scalars 75
NumPy Reference, Release 2.0.0.dev8464
reshape()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
resize()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
round()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
searchsorted()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
setfield()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
setflags()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
sort()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
squeeze()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
std()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
sum()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
swapaxes()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
take()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
tofile()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
tolist()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
1.2. Scalars 77
NumPy Reference, Release 2.0.0.dev8464
See Also:
The
tostring()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
trace()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
transpose()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
var()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
view()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
__array__()
sc.__array__(|type) return 0-dim array
__array_wrap__()
sc.__array_wrap__(obj) return scalar from array
byteswap()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes
of the ndarray class so as to provide a uniform API.
See Also:
The
__reduce__()
__setstate__()
setflags()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes
of the ndarray class so as to provide a uniform API.
See Also:
The
There are two ways to effectively define a new array scalar type (apart from composing record dtypes from the built-in
scalar types): One way is to simply subclass the ndarray and overwrite the methods of interest. This will work to a
degree, but internally certain behaviors are fixed by the data type of the array. To fully customize the data type of an
array you need to define a new data-type, and register it with NumPy. Such new types can only be defined in C, using
the Numpy C-API.
A data type object (an instance of numpy.dtype class) describes how the bytes in the fixed-size block of memory
corresponding to an array item should be interpreted. It describes the following aspects of the data:
1. Type of the data (integer, float, Python object, etc.)
2. Size of the data (how many bytes is in e.g. the integer)
3. Byte order of the data (little-endian or big-endian)
4. If the data type is a record, an aggregate of other data types, (e.g., describing an array item consisting of an
integer and a float),
(a) what are the names of the fields of the record, by which they can be accessed,
(b) what is the data-type of each field, and
(c) which part of the memory block each field takes.
5. If the data is a sub-array, what is its shape and data type.
To describe the type of scalar data, there are several built-in scalar types in Numpy for various precision of integers,
floating-point numbers, etc. An item extracted from an array, e.g., by indexing, will be a Python object whose type is
the scalar type associated with the data type of the array.
Note that the scalar types are not dtype objects, even though they can be used in place of one whenever a data type
specification is needed in Numpy. Record data types are formed by creating a data type whose fields contain other
data types. Each field has a name by which it can be accessed. The parent data type should be of sufficient size to
contain all its fields; the parent can for example be based on the void type which allows an arbitrary item size. Record
data types may also contain other record types and fixed-size sub-array data types in their fields. Finally, a data type
can describe items that are themselves arrays of items of another data type. These sub-arrays must, however, be of a
fixed size. If an array is created using a data-type describing a sub-array, the dimensions of the sub-array are appended
to the shape of the array when the array is created. Sub-arrays in a field of a record behave differently, see Record
Access.
Example
A simple data type containing a 32-bit big-endian integer: (see Specifying and constructing data types for details on
construction)
>>> dt = np.dtype(>i4)
>>> dt.byteorder
>
>>> dt.itemsize
4
>>> dt.name
int32
>>> dt.type is np.int32
True
Items of an array of this data type are wrapped in an array scalar type that also has two fields:
Whenever a data-type is required in a NumPy function or method, either a dtype object or something that can be
converted to one can be supplied. Such conversions are done by the dtype constructor:
dtype Create a data type object.
class dtype()
Create a data type object.
A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be
constructed from different combinations of fundamental numeric types.
Parameters
obj :
Examples
Using array-scalar type:
>>> np.dtype(np.int16)
dtype(int16)
Record, one field named f1, in itself containing a record with one field:
Record, two fields: the first field contains an unsigned int, the second an int32:
>>> np.dtype([(a,f8),(b,S10)])
dtype([(a, <f8), (b, |S10)])
Using tuples. int is a fixed type, 3 the fields shape. void is a flexible type, here of size 10:
>>> np.dtype([(hello,(np.int,3)),(world,np.void,10)])
dtype([(hello, <i4, 3), (world, |V10)])
Subdivide int16 into 2 int8s, called x and y. 0 and 1 are the offsets in bytes:
>>> np.dtype({surname:(S25,0),age:(np.uint8,25)})
dtype([(surname, |S25), (age, |u1)])
Methods
newbyteorder([new_order]) Return a new dtype with a different byte order.
newbyteorder(new_order=S)
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
Parameters
new_order : string, optional
Byte order to force; a value from the byte order specifications below. The default value
(S) results in swapping the current byte order. new_order codes can be any of:
The code does a case-insensitive check on the first letter of new_order for these alterna-
tives. For example, any of > or B or b or brian are valid to specify big-endian.
Returns
new_dtype : dtype
New dtype object with the given change to the byte order.
Notes
Changes are also made in all fields and sub-arrays of the data type.
Examples
Generic types
The generic hierarchical type objects convert to corresponding type objects according to the associations:
number, inexact, floating float
complexfloating cfloat
integer, signedinteger int_
unsignedinteger uint
character string
generic, flexible void
Built-in Python types
Several python types are equivalent to a corresponding array scalar when used to generate a dtype object:
int int_
bool bool_
float float_
complex cfloat
str string
unicode unicode_
buffer void
(all others) object_
Example
Type strings
Any string in numpy.sctypeDict.keys():
Example
(flexible_dtype, itemsize)
The first argument must be an object that is converted to a flexible data-type object (one whose element
size is 0), the second argument is an integer providing the desired itemsize.
Example
(fixed_dtype, shape)
The first argument is any object that can be converted into a fixed-size data-type object. The second
argument is the desired shape of this type. If the shape parameter is 1, then the data-type object is
equivalent to fixed dtype. If shape is a tuple, then the new dtype defines a sub-array of the given shape.
Example
(base_dtype, new_dtype)
Both arguments must be convertible to data-type objects in this case. The base_dtype is the data-type
object that the new data-type builds on. This is how you could assign named fields to any built-in data-
type object.
Example
32-bit integer, whose first two bytes are interpreted as an integer via field real, and the following two
bytes via field imag.
32-bit integer, which is interpreted as consisting of a sub-array of shape (4,) containing 8-bit integers:
32-bit integer, containing fields r, g, b, a that interpret the 4 bytes in the integer as four unsigned integers:
Data type with fields r and b (with the given titles), both being 8-bit unsigned integers, the first at byte
position 0 from the start of the field and the second at position 2:
1.3.2 dtype
Attributes
itemsize
The element size of this data-type object.
For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be
anything.
Endianness of this data:
dtype.byteorder A character indicating the byte-order of this data-type object.
byteorder
A character indicating the byte-order of this data-type object.
One of:
= native
< little-endian
> big-endian
| not applicable
All built-in data-type objects have byteorder either = or |.
Examples
>>> dt = np.dtype(i2)
>>> dt.byteorder
=
>>> # endian is not relevant for 8 bit numbers
>>> np.dtype(i1).byteorder
|
>>> # or ASCII strings
>>> np.dtype(S2).byteorder
|
>>> # Even if specific code is given, and it is native
>>> # = is the byteorder
>>> import sys
>>> sys_is_le = sys.byteorder == little
>>> native_code = sys_is_le and < or >
>>> swapped_code = sys_is_le and > or <
>>> dt = np.dtype(native_code + i2)
>>> dt.byteorder
=
>>> # Swapped code shows up as itself
>>> dt = np.dtype(swapped_code + i2)
>>> dt.byteorder == swapped_code
True
If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields
dictionary, otherwise its meta-data). Notice also that the first two elements of the tuple can be passed directly
as arguments to the ndarray.getfield and ndarray.setfield methods.
See Also:
ndarray.getfield, ndarray.setfield
Examples
names
Ordered list of field names, or None if there are no fields.
The names are ordered according to increasing byte offset. This can be used, for example, to walk through all
of the named fields in offset order.
Examples
flags
Bit-flags describing how this data type is to be interpreted.
Bit-masks are in numpy.core.multiarray as the constants ITEM_HASOBJECT, LIST_PICKLE,
ITEM_IS_POINTER, NEEDS_INIT, NEEDS_PYAPI, USE_GETITEM, USE_SETITEM. A full explanation of
these flags is in C-API documentation; they are largely useful for user-defined data-types.
isbuiltin
Integer indicating how this dtype relates to the built-in dtypes.
Read-only.
0 if this is a structured array type, with fields
1 if this is a dtype compiled into numpy (such as ints, floats etc)
2 if the dtype is for a user-defined numpy type A user-defined type uses the numpy C-API machinery to extend
numpy to handle a new array type. See User-defined data-types (in NumPy User Guide) in the Numpy
manual.
Examples
>>> dt = np.dtype(i2)
>>> dt.isbuiltin
1
>>> dt = np.dtype(f8)
>>> dt.isbuiltin
1
>>> dt = np.dtype([(field1, f8)])
>>> dt.isbuiltin
0
isnative
Boolean indicating whether the byte order of this dtype is native to the platform.
descr
Array-interface compliant full description of the data-type.
The format is that required by the descr key in the __array_interface__ attribute.
alignment
The required alignment (bytes) of this data-type according to the compiler.
More information is available in the C-API section of the manual.
Methods
Data types have the following method for changing the byte order:
dtype.newbyteorder([new_order]) Return a new dtype with a different byte order.
newbyteorder(new_order=S)
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
Parameters
new_order : string, optional
Byte order to force; a value from the byte order specifications below. The default value
(S) results in swapping the current byte order. new_order codes can be any of:
The code does a case-insensitive check on the first letter of new_order for these alter-
natives. For example, any of > or B or b or brian are valid to specify big-endian.
Returns
new_dtype : dtype
New dtype object with the given change to the byte order.
Notes
Changes are also made in all fields and sub-arrays of the data type.
Examples
__setstate__()
1.4 Indexing
ndarrays can be indexed using the standard Python x[obj] syntax, where x is the array and obj the selection.
There are three kinds of indexing available: record access, basic slicing, advanced indexing. Which one occurs
depends on obj.
Note: In Python, x[(exp1, exp2, ..., expN)] is equivalent to x[exp1, exp2, ..., expN]; the
latter is just syntactic sugar for the former.
Basic slicing extends Pythons basic concept of slicing to N dimensions. Basic slicing occurs when obj is a slice
object (constructed by start:stop:step notation inside of brackets), an integer, or a tuple of slice objects and
integers. Ellipsis and newaxis objects can be interspersed with these as well. In order to remain backward
compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any sequence
(such as a list) containing slice objects, the Ellipsis object, or the newaxis object, but no integer arrays or
other embedded sequences. The simplest case of indexing with N integers returns an array scalar representing the
corresponding item. As in Python, all indices are zero-based: for the i-th index ni , the valid range is 0 ni < di
where di is the i-th element of the shape of the array. Negative indices are interpreted as counting from the end of the
array (i.e., if i < 0, it means ni + i).
All arrays generated by basic slicing are always views of the original array.
The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index).
Some useful concepts to remember include:
The basic slice syntax is i:j:k where i is the starting index, j is the stopping index, and k is the step (k 6= 0).
This selects the m elements (in the corresponding dimension) with index values i, i + k, ..., i + (m - 1) k where
m = q + (r 6= 0) and q and r are the quotient and remainder obtained by dividing j - i by k: j - i = q k + r, so
that i + (m - 1) k < j.
Example
Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding
dimension. Negative k makes stepping go towards smaller indices.
Example
>>> x[-2:10]
array([8, 9])
>>> x[-3:3:-1]
array([7, 6, 5, 4])
Assume n is the number of elements in the dimension being sliced. Then, if i is not given it defaults to 0 for k >
0 and n for k < 0 . If j is not given it defaults to n for k > 0 and -1 for k < 0 . If k is not given it defaults to 1.
Note that :: is the same as : and means select all indices along this axis.
Example
>>> x[5:]
array([5, 6, 7, 8, 9])
If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions.
Example
Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim.
Only the first ellipsis is expanded, any others are interpreted as :.
Example
>>> x[...,0]
array([[1, 2, 3],
[4, 5, 6]])
Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one
unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.
Example
>>> x[:,np.newaxis,:,:].shape
(2, 1, 3, 1)
An integer, i, returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1.
In particular, a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding
sub-array with dimension N - 1. If N = 1 then the returned object is an array scalar. These objects are explained
in Scalars.
If the selection tuple has all entries : except the p-th entry which is a slice object i:j:k, then the returned
array has dimension N formed by concatenating the sub-arrays returned by integer indexing of elements i, i+k,
..., i + (m - 1) k < j,
Basic slicing with more than one non-: entry in the slicing tuple, acts like repeated application of slicing using
a single non-: entry, where the non-: entries are successively taken (with all other non-: entries replaced by
:). Thus, x[ind1,...,ind2,:] acts like x[ind1][...,ind2,:] under basic slicing.
You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the
value to be set in x[obj] = value must be (broadcastable) to the same shape as x[obj].
Note: Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. Slice objects
can be used in the construction in place of the [start:stop:step] notation. For example, x[1:10:5,::-1]
can also be implemented as obj = (slice(1,10,5), slice(None,None,-1)); x[obj] . This can be
useful for constructing generic code that works on arrays of arbitrary dimension.
newaxis
The newaxis object can be used in the basic slicing syntax discussed above. None can also be used instead
of newaxis.
1.4. Indexing 93
NumPy Reference, Release 2.0.0.dev8464
Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data
type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are
two types of advanced indexing: integer and Boolean.
Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).
Integer
Integer indexing allows selection of arbitrary items in the array based on their N-dimensional index. This kind of
selection occurs when advanced indexing is triggered and the selection object is not an array of data type bool. For the
discussion below, when the selection object is not a tuple, it will be referred to as if it had been promoted to a 1-tuple,
which will be called the selection tuple. The rules of advanced integer-style indexing are:
If the length of the selection tuple is larger than N an error is raised.
All sequences and scalars in the selection tuple are converted to intp indexing arrays.
All selection tuple objects must be convertible to intp arrays, slice objects, or the Ellipsis object.
The first Ellipsis object will be expanded, and any other Ellipsis objects will be treated as full slice (:)
objects. The expanded Ellipsis object is replaced with as many full slice (:) objects as needed to make the
length of the selection tuple N .
If the selection tuple is smaller than N, then as many : objects as needed are added to the end of the selection
tuple so that the modified selection tuple has length N.
All the integer indexing arrays must be broadcastable to the same shape.
The shape of the output (or the needed shape of the object to be used for setting) is the broadcasted shape.
After expanding any ellipses and filling out any missing : objects in the selection tuple, then let Nt be the
number of indexing arrays, and let Ns = N Nt be the number of slice objects. Note that Nt > 0 (or we
wouldnt be doing advanced integer indexing).
If Ns = 0 then the M-dimensional result is constructed by varying the index tuple (i_1, ..., i_M) over
the range of the result shape and for each value of the index tuple (ind_1, ..., ind_M):
Example
Suppose the shape of the broadcasted indexing arrays is 3-dimensional and N is 2. Then the result is found by
letting i, j, k run over the shape found by broadcasting ind_1 and ind_2, and each i, j, k yields:
If Ns > 0, then partial indexing is done. This can be somewhat mind-boggling to understand, but if you think
in terms of the shapes of the arrays involved, it can be easier to grasp what happens. In simple cases (i.e.
one indexing array and N - 1 slice objects) it does exactly what you would expect (concatenation of repeated
application of basic slicing). The rule for partial indexing is that the shape of the result (or the interpreted shape
of the object to be used in setting) is the shape of x with the indexed subspace replaced with the broadcasted
indexing subspace. If the index subspaces are right next to each other, then the broadcasted indexing space
directly replaces all of the indexed subspaces in x. If the indexing subspaces are separated (by slice objects),
then the broadcasted indexing space is first, followed by the sliced subspace of x.
Example
Suppose x.shape is (10,20,30) and ind is a (2,3,4)-shaped indexing intp array, then result =
x[...,ind,:] has shape (10,2,3,4,30) because the (20,)-shaped subspace has been replaced with a
(2,3,4)-shaped broadcasted indexing subspace. If we let i, j, k loop over the (2,3,4)-shaped subspace then
result[...,i,j,k,:] = x[...,ind[i,j,k],:]. This example produces the same result as
x.take(ind, axis=-2).
Example
Now let x.shape be (10,20,30,40,50) and suppose ind_1 and ind_2 are broadcastable to the shape (2,3,4).
Then x[:,ind_1,ind_2] has shape (10,2,3,4,40,50) because the (20,30)-shaped subspace from X has
been replaced with the (2,3,4) subspace from the indices. However, x[:,ind_1,:,ind_2] has shape
(2,3,4,10,30,50) because there is no unambiguous place to drop in the indexing subspace, thus it is tacked-
on to the beginning. It is always possible to use .transpose() to move the subspace anywhere desired.
(Note that this example cannot be replicated using take.)
Boolean
This advanced indexing occurs when obj is an array object of Boolean type (such as may be returned from com-
parison operators). It is always equivalent to (but faster than) x[obj.nonzero()] where, as described above,
obj.nonzero() returns a tuple (of length obj.ndim) of integer index arrays showing the True elements of obj.
The special case when obj.ndim == x.ndim is worth mentioning. In this case x[obj] returns a 1-dimensional
array filled with the elements of x corresponding to the True values of obj. The search order will be C-style (last
index varies the fastest). If obj has True values at entries that are outside of the bounds of x, then an index error will
be raised.
You can also use Boolean arrays as element of the selection tuple. In such instances, they will always be interpreted
as nonzero(obj) and the equivalent integer indexing will be done.
Warning: The definition of advanced indexing means that x[(1,2,3),] is fundamentally different than
x[(1,2,3)]. The latter is equivalent to x[1,2,3] which will trigger basic selection while the former will
trigger advanced indexing. Be sure to understand why this is occurs.
Also recognize that x[[1,2,3]] will trigger advanced indexing, whereas x[[1,2,slice(None)]] will
trigger basic slicing.
See Also:
Data type objects (dtype), Scalars
If the ndarray object is a record array, i.e. its data type is a record data type, the fields of the array can be accessed
by indexing the array with strings, dictionary-like.
Indexing x[field-name] returns a new view to the array, which is of the same shape as x (except when the field
is a sub-array) but of data type x.dtype[field-name] and contains only the part of the data in the specified
field. Also record array scalars can be indexed this way.
If the accessed field is a sub-array, the dimensions of the sub-array are appended to the shape of the result.
Example
1.4. Indexing 95
NumPy Reference, Release 2.0.0.dev8464
dtype(int32)
>>> x[b].shape
(2, 2, 3, 3)
>>> x[b].dtype
dtype(float64)
x.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying
the fastest). This iterator object can also be indexed using basic slicing or advanced indexing as long as the selection
object is not a tuple. This should be clear from the fact that x.flat is a 1-dimensional view. It can be used for integer
indexing with 1-dimensional C-style-flat indices. The shape of any returned array is therefore the shape of the integer
indexing object.
The ndarray in NumPy is a new-style Python built-in-type. Therefore, it can be inherited from (in Python or in
C) if desired. Therefore, it can form a foundation for many useful classes. Often whether to sub-class the array object
or to simply use the core array component as an internal part of a new class is a difficult decision, and can be simply a
matter of choice. NumPy has several tools for simplifying how your new object interacts with other array objects, and
so the choice may not be significant in the end. One way to simplify the question is by asking yourself if the object
you are interested in can be replaced as a single array or does it really require two or more arrays at its core.
Note that asarray always returns the base-class ndarray. If you are confident that your use of the array object can
handle any subclass of an ndarray, then asanyarray can be used to allow subclasses to propagate more cleanly
through your subroutine. In principal a subclass could redefine any aspect of the array and therefore, under strict
guidelines, asanyarray would rarely be useful. However, most subclasses of the arrayobject will not redefine
certain aspects of the array object such as the buffer interface, or the attributes of the array. One important example,
however, of why your subroutine may not be able to handle an arbitrary subclass of an array is that matrices redefine
the * operator to be matrix-multiplication, rather than element-by-element multiplication.
See Also:
Subclassing ndarray (in NumPy User Guide)
Numpy provides several hooks that subclasses of ndarray can customize:
__array_finalize__(self )
This method is called whenever the system internally allocates a new array from obj, where obj is a subclass
(subtype) of the ndarray. It can be used to change attributes of self after construction (so as to ensure
a 2-d matrix for example), or to update meta-information from the parent. Subclasses inherit a default
implementation of this method that does nothing.
__array_prepare__(array, context=None)
At the beginning of every ufunc, this method is called on the input object with the highest array priority, or the
output object if one was specified. The output array is passed in and whatever is returned is passed to the ufunc.
Subclasses inherit a default implementation of this method which simply returns the output array unmodified.
Subclasses may opt to use this method to transform the output array into an instance of the subclass and update
metadata before returning the array to the ufunc for computation.
__array_wrap__(array, context=None)
At the end of every ufunc, this method is called on the input object with the highest array priority, or the output
object if one was specified. The ufunc-computed array is passed in and whatever is returned is passed to the
user. Subclasses inherit a default implementation of this method, which transforms the array into a new instance
of the objects class. Subclasses may opt to use this method to transform the output array into an instance of the
subclass and update metadata before returning the array to the user.
__array_priority__
The value of this attribute is used to determine what type of object to return in situations where there is more
than one possibility for the Python type of the returned object. Subclasses inherit a default value of 1.0 for this
attribute.
__array__([dtype])
If a class having the __array__ method is used as the output object of an ufunc, results will be written to the
object returned by __array__.
matrix objects inherit from the ndarray and therefore, they have the same attributes and methods of ndarrays. There
are six important differences of matrix objects, however, that may lead to unexpected results when you use matrices
but expect them to act like arrays:
1. Matrix objects can be created using a string notation to allow Matlab-style syntax where spaces separate columns
and semicolons (;) separate rows.
2. Matrix objects are always two-dimensional. This has far-reaching implications, in that m.ravel() is still two-
dimensional (with a 1 in the first dimension) and item selection returns two-dimensional objects so that sequence
behavior is fundamentally different than arrays.
3. Matrix objects over-ride multiplication to be matrix-multiplication. Make sure you understand this for func-
tions that you may want to receive matrices. Especially in light of the fact that asanyarray(m) returns a
matrix when m is a matrix.
4. Matrix objects over-ride power to be matrix raised to a power. The same warning about using power inside a
function that uses asanyarray(...) to get an array object holds for this fact.
5. The default __array_priority__ of matrix objects is 10.0, and therefore mixed operations with ndarrays always
produce matrices.
6. Matrices have special attributes which make calculations easier. These are
matrix.T transpose
matrix.H hermitian (conjugate) transpose
matrix.I inverse
matrix.A base array
T
transpose
H
hermitian (conjugate) transpose
I
inverse
A
base array
Warning: Matrix objects over-ride multiplication, *, and power, **, to be matrix-multiplication and matrix
power, respectively. If your subroutine can accept sub-classes and you do not convert to base- class arrays, then
you must use the ufuncs multiply and power to be sure that you are performing the correct operation for all inputs.
The matrix class is a Python subclass of the ndarray and can be used as a reference for how to construct your own
subclass of the ndarray. Matrices can be created from other matrices, strings, and anything else that can be converted
to an ndarray . The name mat is an alias for matrix in NumPy.
matrix Returns a matrix from an array-like object, or from a string of data.
asmatrix(data[, dtype]) Interpret the input as a matrix.
bmat(obj[, ldict, gdict]) Build a matrix object from a string, nested sequence, or array.
class matrix()
Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-d array that
retains its 2-d nature through operations. It has certain special operators, such as * (matrix multiplication) and
** (matrix power).
Parameters
data : array_like or string
If data is a string, the string is interpreted as a matrix with commas or spaces separating
columns, and semicolons separating rows.
dtype : data-type
Data-type of the output matrix.
copy : bool
If data is already an ndarray, then this flag determines whether the data is copied, or
whether a view is constructed.
See Also:
array
Examples
>>> a = np.matrix(1 2; 3 4)
>>> print a
[[1 2]
[3 4]]
Methods
all([axis, out]) Test whether all matrix elements along a given axis evaluate to True.
any([axis, out]) Test whether any array element along a given axis evaluates to True.
argmax([axis, out]) Indices of the maximum values along an axis.
argmin([axis, out]) Return the indices of the minimum values along an axis.
argsort([axis, kind, order]) Returns the indices that would sort this array.
astype(t) Copy of the array, cast to a specified type.
byteswap(inplace) Swap the bytes of the array elements
choose(choices[, out, mode]) Use an index array to construct a new array from a set of choices.
Continued on next page
all(axis=None, out=None)
Test whether all matrix elements along a given axis evaluate to True.
Parameters
See numpy.all for complete descriptions :
See Also:
numpy.all
Notes
This is the same as ndarray.all, but it returns a matrix object.
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> y = x[0]; y
matrix([[0, 1, 2, 3]])
>>> (x == y)
matrix([[ True, True, True, True],
[False, False, False, False],
[False, False, False, False]], dtype=bool)
>>> (x == y).all()
False
>>> (x == y).all(0)
matrix([[False, False, False, False]], dtype=bool)
>>> (x == y).all(1)
matrix([[ True],
[False],
[False]], dtype=bool)
any(axis=None, out=None)
Test whether any array element along a given axis evaluates to True.
Refer to numpy.any for full documentation.
Parameters
axis: int, optional :
Axis along which logical OR is performed
out: ndarray, optional :
Output to existing array instead of creating new one, must have same shape as expected
output
Returns
any : bool, ndarray
Returns a single bool if axis is None; otherwise, returns ndarray
argmax(axis=None, out=None)
Indices of the maximum values along an axis.
Parameters
See numpy.argmax for complete descriptions :
See Also:
numpy.argmax
Notes
This is the same as ndarray.argmax, but returns a matrix object where ndarray.argmax would return an
ndarray.
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.argmax()
11
>>> x.argmax(0)
matrix([[2, 2, 2, 2]])
>>> x.argmax(1)
matrix([[3],
[3],
[3]])
argmin(axis=None, out=None)
Return the indices of the minimum values along an axis.
Parameters
See numpy.argmin for complete descriptions. :
See Also:
numpy.argmin
Notes
This is the same as ndarray.argmin, but returns a matrix object where ndarray.argmin would return an
ndarray.
Examples
>>> x = -np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, -1, -2, -3],
[ -4, -5, -6, -7],
[ -8, -9, -10, -11]])
>>> x.argmin()
11
>>> x.argmin(0)
matrix([[2, 2, 2, 2]])
>>> x.argmin(1)
matrix([[3],
[3],
[3]])
numpy.argsort
equivalent function
astype(t)
Copy of the array, cast to a specified type.
Parameters
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
>>> x.astype(int)
array([1, 2, 2])
byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, option-
ally swapped in-place.
Parameters
inplace: bool, optional :
If True, swap bytes in-place, default is False.
Returns
out: ndarray :
The byteswapped array. If inplace is True, this is a view to self.
Examples
numpy.choose
equivalent function
numpy.clip
equivalent function
numpy.compress
equivalent function
conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
numpy.cumprod
equivalent function
numpy.cumsum
equivalent function
numpy.diagonal
equivalent function
dot()
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an
array.
Parameters
None :
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
getA()
Return self as an ndarray object.
Equivalent to np.asarray(self).
Parameters
None :
Returns
ret : ndarray
self as an ndarray
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.getA()
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
getA1()
Return self as a flattened ndarray.
Equivalent to np.asarray(x).ravel()
Parameters
None :
Returns
ret : ndarray
self, 1-D, as an ndarray
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.getA1()
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
getH()
Returns the (complex) conjugate transpose of self.
Equivalent to np.transpose(self) if self is real-valued.
Parameters
None :
Returns
ret : matrix object
complex conjugate transpose of self
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4)))
>>> z = x - 1j*x; z
matrix([[ 0. +0.j, 1. -1.j, 2. -2.j, 3. -3.j],
[ 4. -4.j, 5. -5.j, 6. -6.j, 7. -7.j],
[ 8. -8.j, 9. -9.j, 10.-10.j, 11.-11.j]])
>>> z.getH()
matrix([[ 0. +0.j, 4. +4.j, 8. +8.j],
[ 1. +1.j, 5. +5.j, 9. +9.j],
[ 2. +2.j, 6. +6.j, 10.+10.j],
[ 3. +3.j, 7. +7.j, 11.+11.j]])
getI()
Returns the (multiplicative) inverse of invertible self.
Parameters
None :
Returns
ret : matrix object
If self is non-singular, ret is such that ret * self == self * ret ==
np.matrix(np.eye(self[0,:].size) all return True.
Raises
numpy.linalg.linalg.LinAlgError: Singular matrix :
If self is singular.
See Also:
linalg.inv
Examples
getT()
Returns the transpose of the matrix.
Does not conjugate! For the complex conjugate transpose, use getH.
Parameters
None :
Returns
ret : matrix object
The (non-conjugated) transpose of the matrix.
See Also:
transpose, getH
Examples
getfield(dtype, offset)
Returns a field of the given array as a certain type.
A field is a view of the array data with each itemsize determined by the given type and the offset into the
current array, i.e. from offset * dtype.itemsize to (offset+1) * dtype.itemsize.
Parameters
dtype : str
String denoting the data type of the field.
offset : int
Number of dtype.itemsizes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
>>> x.dtype
dtype(complex128)
>>> x.getfield(complex128, 0) # == x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
If the argument dtype is the same as x.dtype, then offset != 0 raises a ValueError:
>>> x.getfield(complex128, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Need 0 <= offset <= 0 for requested type but received offset = 1
>>> x.getfield(float64, 0)
array([[ 1., 0.],
[ 0., 1.]])
>>> x.getfield(float64, 1)
array([[ 1.77658241e-307, 0.00000000e+000],
[ 0.00000000e+000, 1.77658241e-307]])
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which ele-
ment to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument
is interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is
no available Python scalar that would not lose information. Void arrays return a buffer object for item(),
unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This
can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array
using Pythons optimized math.
Examples
itemset()
max(axis=None, out=None)
Return the maximum value along an axis.
Parameters
See amax for complete descriptions :
See Also:
amax, ndarray.max
Notes
This is the same as ndarray.max, but returns a matrix object where ndarray.max would return an ndarray.
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.max()
11
>>> x.max(0)
matrix([[ 8, 9, 10, 11]])
>>> x.max(1)
matrix([[ 3],
[ 7],
[11]])
Notes
Same as ndarray.mean except that, where that returns an ndarray, this returns a matrix object.
Examples
min(axis=None, out=None)
Return the minimum value along an axis.
Parameters
See amin for complete descriptions. :
See Also:
amin, ndarray.min
Notes
This is the same as ndarray.min, but returns a matrix object where ndarray.min would return an ndarray.
Examples
>>> x = -np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, -1, -2, -3],
[ -4, -5, -6, -7],
[ -8, -9, -10, -11]])
>>> x.min()
-11
>>> x.min(0)
newbyteorder(new_order=S)
Return the array with the same data viewed with a different byte order.
Equivalent to:
arr.view(arr.dtype.newbytorder(new_order))
Changes are also made in all fields and sub-arrays of the array data type.
Parameters
new_order : string, optional
Byte order to force; a value from the byte order specifications above. new_order codes
can be any of:
The default value (S) results in swapping the current byte order. The code does a
case-insensitive check on the first letter of new_order for the alternatives above. For
example, any of B or b or biggish are valid to specify big-endian.
Returns
new_arr : array
New array object with the dtype reflecting given change to the byte order.
nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
Notes
Same as ndarray.prod, except, where that returns an ndarray, this returns a matrix object instead.
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.prod()
0
>>> x.prod(0)
matrix([[ 0, 45, 120, 231]])
>>> x.prod(1)
matrix([[ 0],
[ 840],
[7920]])
ptp(axis=None, out=None)
Peak-to-peak (maximum - minimum) value along the given axis.
Refer to numpy.ptp for full documentation.
See Also:
numpy.ptp
Notes
Same as ndarray.ptp, except, where that would return an ndarray object, this returns a matrix object.
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.ptp()
11
>>> x.ptp(0)
matrix([[8, 8, 8, 8]])
>>> x.ptp(1)
matrix([[3],
[3],
[3]])
numpy.put
equivalent function
ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See Also:
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
reshape(shape, order=C)
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See Also:
numpy.reshape
equivalent function
resize(new_shape, refcheck=True)
Change shape and size of array in-place.
Parameters
new_shape : tuple of ints, or n ints
Shape of resized array.
refcheck : bool, optional
If False, reference count will not be checked. Default is True.
Returns
None :
Raises
ValueError :
If a does not own its own data or references or views to it exist, and the data memory
must be changed.
SystemError :
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See Also:
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another
Python object and then reallocate the memory. However, reference counts can increase in other ways so if
you are sure that you have not shared the memory for this array with another Python object, then you may
safely set refcheck to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and re-
shaped:
Enlarging an array: as above, but missing entries are filled with zeros:
>>> c = a
>>> a.resize((1, 1))
...
ValueError: cannot resize an array that has been referenced ...
round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to numpy.around for full documentation.
See Also:
numpy.around
equivalent function
searchsorted(v, side=left)
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See Also:
numpy.searchsorted
equivalent function
Examples
>>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> x
array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323],
[ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323],
[ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
UPDATEIFCOPY flag can never be set to True. The flag WRITEABLE can only be set to True if the array
owns its own memory, or the ultimate owner of the memory exposes a writeable buffer interface, or is a
string. (The exception for string is made so that unpickling can be done without copying memory.)
Parameters
write : bool, optional
Describes whether or not a can be written to.
align : bool, optional
Describes whether or not a is aligned properly for its type.
uic : bool, optional
Describes whether or not a is a copy of another base array.
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There
are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITE-
ABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the com-
piler);
UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is
deallocated, the base array will be updated with the contents of this array.
All flags can be accessed using their first (upper case) letter as well as the full name.
Examples
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True
Parameters
axis : int, optional
Axis along which to sort. Default is -1, which means sort along the last axis.
kind : {quicksort, mergesort, heapsort}, optional
Sorting algorithm. Default is quicksort.
order : list, optional
When a is an array with fields defined, this argument specifies which fields to compare
first, second, etc. Not all fields need be specified.
See Also:
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
Notes
This is the same as ndarray.std, except that where an ndarray would be returned, a matrix object is returned
instead.
Examples
Notes
This is the same as ndarray.sum, except that where an ndarray would be returned, a matrix object is
returned instead.
Examples
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
numpy.take
equivalent function
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision
is lost, so this method is not a good choice for files intended to archive data or transport data between
machines with different endianness. Some of these problems can be overcome by outputting the data as
text files, at the expense of speed and file size.
tolist()
Return the matrix as a (possibly nested) list.
See ndarray.tolist for full documentation.
See Also:
ndarray.tolist
Examples
>>> x = np.matrix(np.arange(12).reshape((3,4))); x
matrix([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> x.tolist()
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
tostring(order=C)
Construct a Python string containing the raw data bytes in the array.
Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced
in either C or Fortran, or Any order (the default is C-order). Any order means C-order unless the
F_CONTIGUOUS flag in the array is set, in which case it means Fortran order.
Parameters
order : {C, F, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original
array.
Returns
s : str
A Python string exhibiting a copy of as raw data.
Examples
numpy.trace
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D ar-
ray into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes
are given, their order indicates how the axes are permuted (see Examples). If axes are not provided
and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape
= (i[n-1], i[n-2], ... i[1], i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s
j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
Notes
This is the same as ndarray.var, except that where an ndarray would be returned, a matrix object is returned
instead.
Examples
view(dtype=None, type=None)
New view of array with the same data.
Parameters
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
type : python type
Type of the returned view, e.g. ndarray or matrix.
Notes
a.view() is used two different ways.
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the arrays memory with a different
dtype. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass), or a.view(type=ndarray_subclass), just returns an instance of ndarray_subclass
that looks at the same array (same shape, dtype, etc.). This does not cause a reinterpretation of the memory.
Examples
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
asmatrix(data, dtype=None)
Interpret the input as a matrix.
Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to
matrix(data, copy=False).
Parameters
data : array_like
Input data.
Returns
mat : matrix
data interpreted as a matrix.
Examples
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
Examples
>>> A = np.mat(1 1; 1 1)
>>> B = np.mat(2 2; 2 2)
>>> C = np.mat(3 4; 5 6)
>>> D = np.mat(7 8; 9 0)
>>> a=mat(1 2 3; 4 5 3)
>>> print (a*a.T).I
[[ 0.2924 -0.1345]
[-0.1345 0.0819]]
>>> mat([[1,5,10],[1.0,3,4j]])
matrix([[ 1.+0.j, 5.+0.j, 10.+0.j],
[ 1.+0.j, 3.+0.j, 0.+4.j]])
>>> mat(random.rand(3,3)).T
matrix([[ 0.7699, 0.7922, 0.3294],
[ 0.2792, 0.0101, 0.9219],
[ 0.3398, 0.7571, 0.8197]])
Memory-mapped files are useful for reading and/or modifying small segments of a large file with regular layout,
without reading the entire file into memory. A simple subclass of the ndarray uses a memory-mapped file for the data
buffer of the array. For small files, the over-head of reading the entire file into memory is typically not significant,
however for large files using memory mapping can save considerable resources.
Memory-mapped-file arrays have one additional method (besides those they inherit from the ndarray): .flush()
which must be called manually by the user to ensure that any changes to the array actually get written to disk.
Note: Memory-mapped arrays use the the Python memory-map object which (prior to Python 2.5) does not allow
files to be larger than a certain size depending on the platform. This size is always < 2GB even on 64-bit systems.
memmap Create a memory-map to an array stored in a binary file on disk.
memmap.flush() Write any changes in the array to the file on disk.
class memmap()
Create a memory-map to an array stored in a binary file on disk.
Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire
file into memory. Numpys memmaps are array-like objects. This differs from Pythons mmap module, which
uses file-like objects.
Parameters
filename : str or file-like object
The file name or file object to be used as the array data buffer.
dtype : data-type, optional
The data-type used to interpret the file contents. Default is uint8.
mode : {r+, r, w+, c}, optional
The file is opened in this mode:
r Open existing file for reading only.
r+ Open existing file for reading and writing.
w+ Create or overwrite existing file for reading and writing.
c Copy-on-write: assignments affect data in memory, but changes are not saved to disk. The file on disk is
read-only.
Default is r+.
offset : int, optional
In the file, array data starts at this offset. Since offset is measured in bytes, it should be
a multiple of the byte-size of dtype. Requires shape=None. The default is 0.
shape : tuple, optional
The desired shape of the array. By default, the returned array will be 1-D with the
number of elements determined by file size and data-type.
order : {C, F}, optional
Specify the order of the ndarray memory layout: C (row-major) or Fortran (column-
major). This only has an effect if the shape is greater than 1-D. The default order is
C.
Notes
The memmap object can be used anywhere an ndarray is accepted. Given a memmap fp, isinstance(fp,
numpy.ndarray) returns True.
Memory-mapped arrays use the Python memory-map object which (prior to Python 2.5) does not allow files to
be larger than a certain size depending on the platform. This size is always < 2GB even on 64-bit systems.
Examples
This example uses a temporary file so that doctest doesnt write files to your directory. You would use a normal
filename.
Create a memmap with dtype and shape that matches our data:
>>> del fp
Read-only memmap:
Copy-on-write memmap:
Its possible to assign to copy-on-write array, but values are only written into the memory copy of the array, and
not written to disk:
>>> fpc
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> fpc[0,:] = 0
>>> fpc
memmap([[ 0., 0., 0., 0.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> fpr
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
Attributes
filename str Path to the mapped file.
offset int Offset position in the file.
mode str File mode.
Methods
close() Close the memmap file.
flush() Write any changes in the array to the file on disk.
close()
Close the memmap file. Does nothing.
flush()
Write any changes in the array to the file on disk.
For further information, see memmap.
Parameters
None :
See Also:
memmap
flush()
Write any changes in the array to the file on disk.
For further information, see memmap.
Parameters
None :
See Also:
memmap
Example:
See Also:
Creating character arrays (numpy.char)
Note: The chararray class exists for backwards compatibility with Numarray, it is not recommended for new devel-
opment. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_,
string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations.
These are enhanced arrays of either string_ type or unicode_ type. These arrays inherit from the ndarray,
but specially-define the operations +, *, and % on a (broadcasting) element-by-element basis. These operations are
not available on the standard ndarray of character type. In addition, the chararray has all of the standard
string (and unicode) methods, executing them on an element-by-element basis. Perhaps the easiest way to create
a chararray is to use self.view(chararray) where self is an ndarray of str or unicode data-type. However, a
chararray can also be created using the numpy.chararray constructor, or via the numpy.char.array function:
chararray Provides a convenient view on arrays of string and unicode
values.
core.defchararray.array(obj[, itemsize, Create a chararray.
...])
class chararray()
Provides a convenient view on arrays of string and unicode values.
Note: The chararray class exists for backwards compatibility with Numarray, it is not recommended for new
development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype
object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string
operations.
Versus a regular Numpy array of type str or unicode, this class adds the following functionality:
1.values automatically have whitespace removed from the end when indexed
2.comparison operators automatically remove whitespace from the end when comparing values
3.vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*",
"%")
chararrays should be created using numpy.char.array or numpy.char.asarray, rather than this con-
structor directly.
This constructor creates the array, using buffer (with offset and strides) if it is not None. If buffer is None, then
constructs a new array with strides in C order, unless both len(shape) >= 2 and order=Fortran,
in which case strides is in Fortran order.
Parameters
shape : tuple
Shape of the array.
itemsize : int, optional
Length of each array element, in number of characters. Default is 1.
unicode : bool, optional
Are the array elements of type unicode (True) or string (False). Default is False.
Examples
Methods
astype(t)
Copy of the array, cast to a specified type.
Parameters
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
>>> x.astype(int)
array([1, 2, 2])
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an
array.
Parameters
None :
encode(encoding=None, errors=None)
Calls str.encode element-wise.
See Also:
char.encode
endswith(suffix, start=0, end=None)
Returns a boolean array which is True where the string element in self ends with suffix, otherwise False.
See Also:
char.endswith
expandtabs(tabsize=8)
Return a copy of each string element where all tab characters are replaced by one or more spaces.
See Also:
char.expandtabs
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
getfield(dtype, offset)
Returns a field of the given array as a certain type.
A field is a view of the array data with each itemsize determined by the given type and the offset into the
current array, i.e. from offset * dtype.itemsize to (offset+1) * dtype.itemsize.
Parameters
dtype : str
String denoting the data type of the field.
offset : int
Number of dtype.itemsizes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
>>> x.dtype
dtype(complex128)
>>> x.getfield(complex128, 0) # == x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
If the argument dtype is the same as x.dtype, then offset != 0 raises a ValueError:
>>> x.getfield(complex128, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Need 0 <= offset <= 0 for requested type but received offset = 1
>>> x.getfield(float64, 0)
array([[ 1., 0.],
[ 0., 1.]])
>>> x.getfield(float64, 1)
array([[ 1.77658241e-307, 0.00000000e+000],
[ 0.00000000e+000, 1.77658241e-307]])
See Also:
char.islower
isnumeric()
For each element in self, return True if there are only numeric characters in the element.
See Also:
char.isnumeric
isspace()
Returns true for each element if there are only whitespace characters in the string and there is at least one
character, false otherwise.
See Also:
char.isspace
istitle()
Returns true for each element if the element is a titlecased string and there is at least one character, false
otherwise.
See Also:
char.istitle
isupper()
Returns true for each element if all cased characters in the string are uppercase and there is at least one
character, false otherwise.
See Also:
char.isupper
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which ele-
ment to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument
is interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is
no available Python scalar that would not lose information. Void arrays return a buffer object for item(),
unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This
can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array
using Pythons optimized math.
Examples
join(seq)
Return a string which is the concatenation of the strings in the sequence seq.
See Also:
char.join
ljust(width, fillchar= )
Return an array with the elements of self left-justified in a string of length width.
See Also:
char.ljust
lower()
Return an array with the elements of self converted to lowercase.
See Also:
char.lower
lstrip(chars=None)
For each element in self, return a copy with the leading characters removed.
See Also:
char.lstrip
nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
numpy.put
equivalent function
ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See Also:
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
numpy.reshape
equivalent function
resize(new_shape, refcheck=True)
Change shape and size of array in-place.
Parameters
new_shape : tuple of ints, or n ints
Shape of resized array.
refcheck : bool, optional
If False, reference count will not be checked. Default is True.
Returns
None :
Raises
ValueError :
If a does not own its own data or references or views to it exist, and the data memory
must be changed.
SystemError :
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another
Python object and then reallocate the memory. However, reference counts can increase in other ways so if
you are sure that you have not shared the memory for this array with another Python object, then you may
safely set refcheck to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and re-
shaped:
Enlarging an array: as above, but missing entries are filled with zeros:
>>> c = a
>>> a.resize((1, 1))
...
ValueError: cannot resize an array that has been referenced ...
numpy.searchsorted
equivalent function
See Also:
getfield
Examples
>>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> x
array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323],
[ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323],
[ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There
are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITE-
ABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the com-
piler);
UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is
deallocated, the base array will be updated with the contents of this array.
All flags can be accessed using their first (upper case) letter as well as the full name.
Examples
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
split(sep=None, maxsplit=None)
For each element in self, return a list of the words in the string, using sep as the delimiter string.
See Also:
char.split
splitlines(keepends=None)
For each element in self, return a list of the lines in the element, breaking at line boundaries.
See Also:
char.splitlines
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
See Also:
numpy.swapaxes
equivalent function
swapcase()
For each element in self, return a copy of the string with uppercase characters converted to lowercase and
vice versa.
See Also:
char.swapcase
take(indices, axis=None, out=None, mode=raise)
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See Also:
numpy.take
equivalent function
title()
For each element in self, return a titlecased version of the string: words start with uppercase characters, all
remaining cased characters are lowercase.
See Also:
char.title
tofile(fid, sep="", format="%s")
Write array to a file as text or binary (default).
Data is always written in C order, independent of the order of a. The data produced by this method can
be recovered using the function fromfile().
Parameters
fid : file or str
An open file object, or a string containing a filename.
sep : str
Separator between array items for text output. If (empty), a binary file is written,
equivalent to file.write(a.tostring()).
format : str
Format string for text file output. Each entry in the array is formatted to text by first
converting it to the closest Python type, and then using format % item.
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision
is lost, so this method is not a good choice for files intended to archive data or transport data between
machines with different endianness. Some of these problems can be overcome by outputting the data as
text files, at the expense of speed and file size.
tolist()
Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible
Python type.
Parameters
none :
Returns
y : list
The possibly nested list of array elements.
Notes
The array may be recreated, a = np.array(a.tolist()).
Examples
tostring(order=C)
Construct a Python string containing the raw data bytes in the array.
Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced
in either C or Fortran, or Any order (the default is C-order). Any order means C-order unless the
F_CONTIGUOUS flag in the array is set, in which case it means Fortran order.
Parameters
order : {C, F, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original
array.
Returns
s : str
A Python string exhibiting a copy of as raw data.
Examples
translate(table, deletechars=None)
For each element in self, return a copy of the string where all characters occurring in the optional argument
deletechars are removed, and the remaining characters have been mapped through the given translation
table.
See Also:
char.translate
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D ar-
ray into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes
are given, their order indicates how the axes are permuted (see Examples). If axes are not provided
and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape
= (i[n-1], i[n-2], ... i[1], i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s
j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
upper()
Return an array with the elements of self converted to uppercase.
See Also:
char.upper
view(dtype=None, type=None)
New view of array with the same data.
Parameters
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
Notes
a.view() is used two different ways.
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the arrays memory with a different
dtype. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass), or a.view(type=ndarray_subclass), just returns an instance of ndarray_subclass
that looks at the same array (same shape, dtype, etc.). This does not cause a reinterpretation of the memory.
Examples
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
zfill(width)
Return the numeric string left-filled with zeros in a string of length width.
See Also:
char.zfill
array(obj, itemsize=None, copy=True, unicode=None, order=None)
Create a chararray.
Note: This class is provided for numarray backward-compatibility. New code (not concerned with numarray
compatibility) should use arrays of type string_ or unicode_ and use the free functions in numpy.char for
fast vectorized string operations instead.
Versus a regular Numpy array of type str or unicode, this class adds the following functionality:
1.values automatically have whitespace removed from the end when indexed
2.comparison operators automatically remove whitespace from the end when comparing values
3.vectorized string operations are provided as methods (e.g. str.endswith) and infix operators (e.g. +, *, %)
Parameters
obj : array of str or unicode-like
itemsize : int, optional
itemsize is the number of characters per scalar in the resulting array. If itemsize is
None, and obj is an object array or a Python list, the itemsize will be automatically
determined. If itemsize is provided and obj is of type str or unicode, then the obj string
will be chunked into itemsize pieces.
copy : bool, optional
If true (default), then the object is copied. Otherwise, a copy will only be made if
__array__ returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy
any of the other requirements (itemsize, unicode, order, etc.).
unicode : bool, optional
When true, the resulting chararray can contain Unicode characters, when false only
8-bit characters. If unicode is None and obj is one of the following:
a chararray,
an ndarray of type str or unicode
a Python str or unicode object,
then the unicode setting of the output array will be automatically determined.
order : {C, F, A}, optional
Specify the order of the array. If order is C (default), then the array will be in C-
contiguous order (last-index varies the fastest). If order is F, then the returned array
will be in Fortran-contiguous order (first-index varies the fastest). If order is A, then
the returned array may be in any order (either C-, Fortran-contiguous, or even discon-
tiguous).
Another difference with the standard ndarray of str data-type is that the chararray inherits the feature introduced by
Numarray that white-space at the end of any element in the array will be ignored on item retrieval and comparison
operations.
See Also:
Creating record arrays (numpy.rec), Data type routines, Data type objects (dtype).
Numpy provides the recarray class which allows accessing the fields of a record/structured array as attributes, and
a corresponding scalar data type object record.
recarray Construct an ndarray that allows field access using attributes.
record A data-type scalar that allows field access as attribute lookup.
class recarray()
Construct an ndarray that allows field access using attributes.
Arrays may have a data-types containing fields, analogous to columns in a spread sheet. An example is [(x,
int), (y, float)], where each entry in the array is a pair of (int, float). Normally, these attributes
are accessed using dictionary lookups such as arr[x] and arr[y]. Record arrays allow the fields to be
accessed as members of the array, using arr.x and arr.y.
Parameters
shape : tuple
Shape of output array.
dtype : data-type, optional
The desired data-type. By default, the data-type is determined from formats, names,
titles, aligned and byteorder.
formats : list of data-types, optional
A list containing the data-types for the different columns, e.g. [i4, f8,
i4]. formats does not support the new convention of using types directly, i.e.
(int, float, int). Note that formats must be a list, not a tuple. Given that
formats is somewhat limited, we recommend specifying dtype instead.
names : tuple of str, optional
The name of each column, e.g. (x, y, z).
buf : buffer, optional
By default, a new array is created of the given shape and data-type. If buf is specified
and is an object exposing the buffer interface, the array will use the memory from the
existing buffer. In this case, the offset and strides keywords are available.
Returns
rec : recarray
Empty array of the given shape and type.
See Also:
rec.fromrecords
Construct a record array from data.
record
fundamental data-type for recarray.
format_parser
determine a data-type from formats, names, titles.
Notes
This constructor can be compared to empty: it creates a new record array but does not fill it with data. To create
a record array from data, use one of the following methods:
1.Create a standard ndarray and convert it to a record array, using arr.view(np.recarray)
Examples
Create an array with two fields, x and y:
>>> x[x]
array([ 1., 3.])
>>> x = x.view(np.recarray)
>>> x.x
array([ 1., 3.])
>>> x.y
array([2, 4])
>>> np.recarray((2,),
... dtype=[(x, int), (y, float), (z, int)])
rec.array([(-1073741821, 1.2249118382103472e-301, 24547520),
(3471280, 1.2134086255804012e-316, 0)],
dtype=[(x, <i4), (y, <f8), (z, <i4)])
Methods
all(axis=None, out=None)
Returns True if all elements evaluate to True.
Refer to numpy.all for full documentation.
See Also:
numpy.all
equivalent function
any(axis=None, out=None)
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
See Also:
numpy.any
equivalent function
argmax(axis=None, out=None)
Return indices of the maximum values along the given axis.
Refer to numpy.argmax for full documentation.
See Also:
numpy.argmax
equivalent function
argmin(axis=None, out=None)
Return indices of the minimum values along the given axis of a.
Refer to numpy.argmin for detailed documentation.
See Also:
numpy.argmin
equivalent function
numpy.argsort
equivalent function
astype(t)
Copy of the array, cast to a specified type.
Parameters
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
>>> x.astype(int)
array([1, 2, 2])
byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, option-
ally swapped in-place.
Parameters
inplace: bool, optional :
Examples
numpy.choose
equivalent function
numpy.clip
equivalent function
numpy.compress
equivalent function
conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
numpy.cumprod
equivalent function
See Also:
numpy.cumsum
equivalent function
numpy.diagonal
equivalent function
dot()
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an
array.
Parameters
None :
field(attr, val=None)
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
getfield(dtype, offset)
Returns a field of the given array as a certain type.
A field is a view of the array data with each itemsize determined by the given type and the offset into the
current array, i.e. from offset * dtype.itemsize to (offset+1) * dtype.itemsize.
Parameters
dtype : str
String denoting the data type of the field.
offset : int
Number of dtype.itemsizes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
>>> x.dtype
dtype(complex128)
>>> x.getfield(complex128, 0) # == x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
If the argument dtype is the same as x.dtype, then offset != 0 raises a ValueError:
>>> x.getfield(complex128, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Need 0 <= offset <= 0 for requested type but received offset = 1
>>> x.getfield(float64, 0)
array([[ 1., 0.],
[ 0., 1.]])
>>> x.getfield(float64, 1)
array([[ 1.77658241e-307, 0.00000000e+000],
[ 0.00000000e+000, 1.77658241e-307]])
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which ele-
ment to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument
is interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is
no available Python scalar that would not lose information. Void arrays return a buffer object for item(),
unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This
can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array
using Pythons optimized math.
Examples
itemset()
max(axis=None, out=None)
Return the maximum along a given axis.
Refer to numpy.amax for full documentation.
See Also:
numpy.amax
equivalent function
numpy.mean
equivalent function
min(axis=None, out=None)
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See Also:
numpy.amin
equivalent function
newbyteorder(new_order=S)
Return the array with the same data viewed with a different byte order.
Equivalent to:
arr.view(arr.dtype.newbytorder(new_order))
Changes are also made in all fields and sub-arrays of the array data type.
Parameters
new_order : string, optional
Byte order to force; a value from the byte order specifications above. new_order codes
can be any of:
The default value (S) results in swapping the current byte order. The code does a
case-insensitive check on the first letter of new_order for the alternatives above. For
example, any of B or b or biggish are valid to specify big-endian.
Returns
new_arr : array
New array object with the dtype reflecting given change to the byte order.
nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
numpy.prod
equivalent function
ptp(axis=None, out=None)
Peak to peak (maximum - minimum) value along a given axis.
Refer to numpy.ptp for full documentation.
See Also:
numpy.ptp
equivalent function
numpy.put
equivalent function
ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See Also:
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
reshape(shape, order=C)
Returns an array containing the same data with a new shape.
Refer to numpy.reshape for full documentation.
See Also:
numpy.reshape
equivalent function
resize(new_shape, refcheck=True)
Change shape and size of array in-place.
Parameters
new_shape : tuple of ints, or n ints
Shape of resized array.
refcheck : bool, optional
If False, reference count will not be checked. Default is True.
Returns
None :
Raises
ValueError :
If a does not own its own data or references or views to it exist, and the data memory
must be changed.
SystemError :
If the order keyword argument is specified. This behaviour is a bug in NumPy.
See Also:
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another
Python object and then reallocate the memory. However, reference counts can increase in other ways so if
you are sure that you have not shared the memory for this array with another Python object, then you may
safely set refcheck to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and re-
shaped:
Enlarging an array: as above, but missing entries are filled with zeros:
>>> c = a
>>> a.resize((1, 1))
...
ValueError: cannot resize an array that has been referenced ...
round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to numpy.around for full documentation.
See Also:
numpy.around
equivalent function
searchsorted(v, side=left)
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See Also:
numpy.searchsorted
equivalent function
Examples
>>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> x
array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323],
[ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323],
[ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There
are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITE-
ABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the com-
piler);
UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is
deallocated, the base array will be updated with the contents of this array.
All flags can be accessed using their first (upper case) letter as well as the full name.
Examples
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
numpy.std
equivalent function
numpy.sum
equivalent function
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
numpy.take
equivalent function
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision
is lost, so this method is not a good choice for files intended to archive data or transport data between
machines with different endianness. Some of these problems can be overcome by outputting the data as
text files, at the expense of speed and file size.
tolist()
Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible
Python type.
Parameters
none :
Returns
y : list
The possibly nested list of array elements.
Notes
The array may be recreated, a = np.array(a.tolist()).
Examples
tostring(order=C)
Construct a Python string containing the raw data bytes in the array.
Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced
in either C or Fortran, or Any order (the default is C-order). Any order means C-order unless the
F_CONTIGUOUS flag in the array is set, in which case it means Fortran order.
Parameters
order : {C, F, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original
array.
Returns
s : str
A Python string exhibiting a copy of as raw data.
Examples
See Also:
numpy.trace
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D ar-
ray into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes
are given, their order indicates how the axes are permuted (see Examples). If axes are not provided
and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape
= (i[n-1], i[n-2], ... i[1], i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s
j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
numpy.var
equivalent function
view(dtype=None, type=None)
class record()
A data-type scalar that allows field access as attribute lookup.
Methods
all()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
any()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
argmax()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
argmin()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
argsort()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
astype()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
byteswap()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
choose()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
clip()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
compress()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
conj()
conjugate()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
copy()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
cumprod()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
cumsum()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
diagonal()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
dump()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
dumps()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
fill()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
flatten()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
getfield()
item()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
itemset()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
max()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
mean()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
min()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
newbyteorder(new_order=S)
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
The new_order code can be any from the following:
{<, L} - little endian
{>, B} - big endian
{=, N} - native order
Parameters
new_order : str, optional
Byte order to force; a value from the byte order specifications above. The default value
(S) results in swapping the current byte order. The code does a case-insensitive check
on the first letter of new_order for the alternatives above. For example, any of B or b
or biggish are valid to specify big-endian.
Returns
new_dtype : dtype
New dtype object with the given change to the byte order.
nonzero()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
pprint()
Pretty-print all fields.
prod()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
ptp()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
put()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
ravel()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
repeat()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
reshape()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
resize()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
round()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
searchsorted()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
setfield()
setflags()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
sort()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
squeeze()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
std()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
sum()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
swapaxes()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
take()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
tofile()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
tolist()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
tostring()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
trace()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
transpose()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
var()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
view()
Not implemented (virtual attribute)
Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the
attributes of the ndarray class so as to provide a uniform API.
See Also:
The
See Also:
Masked arrays
For backward compatibility and as a standard container class, the UserArray from Numeric has been brought over to
NumPy and named numpy.lib.user_array.container The container class is a Python class whose self.array
attribute is an ndarray. Multiple inheritance is probably easier with numpy.lib.user_array.container than with the
ndarray itself and so it is included by default. It is not documented here beyond mentioning its existence because you
are encouraged to use the ndarray class directly if you can.
numpy.lib.user_array.container(data[, ...])
class container(data, dtype=None, copy=True)
Iterators are a powerful concept for array processing. Essentially, iterators implement a generalized for-loop. If myiter
is an iterator object, then the Python code:
calls val = myiter.next() repeatedly until StopIteration is raised by the iterator. There are several ways
to iterate over an array that may be useful: default iteration, flat iteration, and N -dimensional enumeration.
Default iteration
The default iterator of an ndarray object is the default Python iterator of a sequence type. Thus, when the array object
itself is used as an iterator. The default behavior is equivalent to:
for i in arr.shape[0]:
val = arr[i]
This default iterator selects a sub-array of dimension N 1 from the array. This can be a useful construct for defining
recursive algorithms. To loop over the entire array requires N for-loops.
>>> a = arange(24).reshape(3,2,4)+10
>>> for val in a:
... print item:, val
item: [[10 11 12 13]
[14 15 16 17]]
item: [[18 19 20 21]
[22 23 24 25]]
item: [[26 27 28 29]
[30 31 32 33]]
Flat iteration
flatten
Return a copy of the array collapsed into one dimension.
flatiter
Examples
An assignment example:
>>> x.flat = 3; x
array([[3, 3, 3],
[3, 3, 3]])
>>> x.flat[[1,4]] = 1; x
array([[3, 1, 3],
[3, 1, 3]])
As mentioned previously, the flat attribute of ndarray objects returns an iterator that will cycle over the entire array in
C-style contiguous order.
Here, Ive used the built-in enumerate iterator to return the iterator index as well as the value.
N-dimensional enumeration
Examples
Methods
next() Standard iterator method, returns the index tuple and array value.
next()
Standard iterator method, returns the index tuple and array value.
Returns
coords : tuple of ints
The indices of the current iteration.
val : scalar
The array element of the current iteration.
Sometimes it may be useful to get the N-dimensional index while iterating. The ndenumerate iterator can achieve this.
Parameters
in1, in2, ... : array_like
Input parameters.
Returns
b : broadcast object
Broadcast the input parameters against one another, and return an object that encapsu-
lates the result. Amongst others, it has shape and nd properties, and may be used as
an iterator.
Examples
Manually adding two vectors, using broadcasting:
>>> x + y
array([[5, 6, 7],
[6, 7, 8],
[7, 8, 9]])
Methods
next x.next() -> the next value, or raise StopIteration
reset
next()
x.next() -> the next value, or raise StopIteration
reset()
The general concept of broadcasting is also available from Python using the broadcast iterator. This object takes
N objects as inputs and returns an iterator that returns tuples providing each of the input sequence elements in the
broadcasted result.
Masked arrays are arrays that may have missing or invalid entries. The numpy.ma module provides a nearly work-
alike replacement for numpy that supports data arrays with masks.
Rationale
Masked arrays are arrays that may have missing or invalid entries. The numpy.ma module provides a nearly work-
alike replacement for numpy that supports data arrays with masks.
In many circumstances, datasets can be incomplete or tainted by the presence of invalid data. For example, a sensor
may have failed to record a data, or recorded an invalid value. The numpy.ma module provides a convenient way to
address this issue, by introducing masked arrays.
A masked array is the combination of a standard numpy.ndarray and a mask. A mask is either nomask, indicating
that no value of the associated array is invalid, or an array of booleans that determines for each element of the associated
array whether the value is valid or not. When an element of the mask is False, the corresponding element of the
associated array is valid and is said to be unmasked. When an element of the mask is True, the corresponding element
of the associated array is said to be masked (invalid).
The package ensures that masked entries are not used in computations.
As an illustration, lets consider the following dataset:
We wish to mark the fourth entry as invalid. The easiest is to create a masked array:
We can now compute the mean of the dataset, without taking the invalid data into account:
>>> mx.mean()
2.75
The main feature of the numpy.ma module is the MaskedArray class, which is a subclass of numpy.ndarray.
The class, its attributes and methods are described in more details in the MaskedArray class section.
The numpy.ma module can be used as an addition to numpy:
To create a masked array where all values close to 1.e20 are invalid, we would do:
For a complete discussion of creation methods for masked arrays please see section Constructing masked arrays.
Parameters
data : array_like
Input data.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same shape as data. True
indicates a masked (i.e. invalid) data.
dtype : dtype, optional
Data type of the output. If dtype is None, the type of the data argument (data.dtype)
is used. If dtype is not None and different from data.dtype, a copy is performed.
copy : bool, optional
Whether to copy the input data (True), or to use a reference instead. Default is False.
subok : bool, optional
Whether to return a subclass of MaskedArray if possible (True) or a plain MaskedArray.
Default is True.
ndmin : int, optional
Minimum number of dimensions. Default is 0.
masked_array
alias of MaskedArray
A third option is to take the view of an existing array. In that case, the mask of the view is set to nomask if the
array has no named fields, or an array of boolean with the same structure as the array otherwise.
No copy is performed if the input is already an ndarray. If a is a subclass of MaskedArray, a base class
MaskedArray is returned.
Parameters
a : array_like
Input data, in any form that can be converted to a masked array. This includes lists, lists
of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {C, F}, optional
Whether to use row-major (C) or column-major (FORTRAN) memory representa-
tion. Default is C.
Returns
out : MaskedArray
Masked array interpretation of a.
See Also:
asanyarray
Similar to asarray, but conserves subclasses.
Examples
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asarray(x))
<class numpy.ma.core.MaskedArray>
asanyarray(a, dtype=None)
Convert the input to a masked array, conserving subclasses.
If a is a subclass of MaskedArray, its class is conserved. No copy is performed if the input is already an
ndarray.
Parameters
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {C, F}, optional
Whether to use row-major (C) or column-major (FORTRAN) memory representa-
tion. Default is C.
Returns
out : MaskedArray
MaskedArray interpretation of a.
See Also:
asarray
Similar to asanyarray, but does not conserve subclass.
Examples
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asanyarray(x))
<class numpy.ma.core.MaskedArray>
Notes
A copy is performed by default.
Examples
>>> np.ma.fix_invalid(x)
masked_array(data = [-- -1.0 -- --],
mask = [ True False True True],
fill_value = 1e+20)
masked_where
Mask where a condition is met.
masked_values
Mask using floating point equality.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Notes
The array x is prefilled with its filling value.
Examples
masked_invalid(a, copy=True)
Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to masked_where, with condition = ~(np.isfinite(a)). Any pre-existing mask
is conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types),
but accepts any array_like object.
See Also:
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
masked_values
Mask using floating point equality.
Examples
>>> eat
masked_array(data = [cheese ham pineapple],
mask = False,
fill_value=?)
masked_where
Mask where a condition is met.
Notes
The array x is prefilled with its filling value.
Examples
The fill_value is set to value and the mask is set to nomask if possible. For integers, consider using
masked_equal.
Parameters
x : array_like
Array to mask.
value : float
Masking value.
rtol : float, optional
Tolerance parameter.
atol : float, optional
Tolerance parameter (1e-8).
copy : bool, optional
Whether to return a copy of x.
shrink : bool, optional
Whether to collapse a mask full of False to nomask.
Returns
result : MaskedArray
The result of masking x where approximately equal to value.
See Also:
masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
Examples
For integers, the fill value will be different in general to the result of masked_equal.
>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> ma.masked_values(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=2)
>>> ma.masked_equal(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=999999)
masked_where(condition, a, copy=True)
Mask an array where a condition is met.
Return a as an array masked where condition is True. Any masked values of a or condition are also masked
in the output.
Parameters
condition : array_like
Masking condition. When condition tests floating point values for equality, consider
using masked_values instead.
a : array_like
Array to mask.
copy : bool
If True (default) make a copy of a in the result. If False modify a in place and return a
view.
Returns
result : MaskedArray
The result of masking a where condition is True.
See Also:
masked_values
Mask using floating point equality.
masked_equal
Mask where equal to a given value.
masked_not_equal
Mask where not equal to a given value.
masked_less_equal
Mask where less than or equal to a given value.
masked_greater_equal
Mask where greater than or equal to a given value.
masked_less
Mask where less than a given value.
masked_greater
Mask where greater than a given value.
masked_inside
Mask inside a given interval.
masked_outside
Mask outside a given interval.
masked_invalid
Mask invalid values (NaNs or infs).
Examples
>>> b = [a, b, c, d]
>>> ma.masked_where(a == 2, b)
masked_array(data = [a b -- d],
mask = [False False True False],
fill_value=N/A)
>>> a = np.arange(4)
>>> a = ma.masked_where(a == 2, a)
>>> a
masked_array(data = [0 1 -- 3],
mask = [False False True False],
fill_value=999999)
>>> b = np.arange(4)
>>> b = ma.masked_where(b == 0, b)
>>> b
masked_array(data = [-- 1 2 3],
The mask of a masked array is accessible through its mask attribute. We must keep in mind that a True entry in the
mask indicates an invalid data.
Another possibility is to use the getmask and getmaskarray functions. getmask(x) outputs the mask of x if
x is a masked array, and the special value nomask otherwise. getmaskarray(x) outputs the mask of x if x is a
masked array. If x has no invalid entry or is not a masked array, the function outputs a boolean array of False with
as many elements as x.
To retrieve only the valid entries, we can use the inverse of the mask as an index. The inverse of the mask can be
calculated with the numpy.logical_not function or simply with the ~ operator:
Another way to retrieve the valid data is to use the compressed method, which returns a one-dimensional ndarray
(or one of its subclasses, depending on the value of the baseclass attribute):
>>> x.compressed()
array([1, 4])
Masking an entry
The recommended way to mark one or several specific entries of a masked array as invalid is to assign the special
value masked to them:
A second possibility is to modify the mask directly, but this usage is discouraged.
Note: When creating a new masked array with a simple, non-structured datatype, the mask is initially set to the
special value nomask, that corresponds roughly to the boolean False. Trying to set an element of nomask will fail
with a TypeError exception, as a boolean does not support item assignment.
All the entries of an array can be masked at once by assigning True to the mask:
Finally, specific entries can be masked and/or unmasked by assigning to the mask a sequence of booleans:
Unmasking an entry
To unmask one or several specific entries, we can just assign one or several new valid values to them:
Note: Unmasking an entry by direct assignment will silently fail if the masked array has a hard mask, as shown by
the hardmask attribute. This feature was introduced to prevent overwriting the mask. To force the unmasking of an
entry where the array has a hard mask, the mask must first to be softened using the soften_mask method before the
allocation. It can be re-hardened with harden_mask:
To unmask all masked entries of a masked array (provided the mask isnt a hard mask), the simplest solution is to
assign the constant nomask to the mask:
As a MaskedArray is a subclass of numpy.ndarray, it inherits its mechanisms for indexing and slicing.
When accessing a single entry of a masked array with no named fields, the output is either a scalar (if the corresponding
entry of the mask is False) or the special value masked (if the corresponding entry of the mask is True):
If the masked array has named fields, accessing a single entry returns a numpy.void object if none of the fields are
masked, or a 0d masked array with the same dtype as the initial array if at least one of the fields is masked.
When accessing a slice, the output is a masked array whose data attribute is a view of the original data, and whose
mask is either nomask (if there was no invalid entries in the original array) or a copy of the corresponding slice of the
original mask. The copy is required to avoid propagation of any modification of the mask to the original.
Arithmetic and comparison operations are supported by masked arrays. As much as possible, invalid entries of a
masked array are not processed, meaning that the corresponding data entries should be the same before and after the
operation.
Warning: We need to stress that this behavior may not be systematic, that masked data may be affected by the
operation in some cases and therefore users should not rely on this data remaining unchanged.
The numpy.ma module comes with a specific implementation of most ufuncs. Unary and binary functions that have a
validity domain (such as log or divide) return the masked constant whenever the input is masked or falls outside
the validity domain:
Masked arrays also support standard numpy ufuncs. The output is then a masked array. The result of a unary ufunc is
masked wherever the input is masked. The result of a binary ufunc is masked wherever any of the input is masked. If
the ufunc also returns the optional context output (a 3-element tuple containing the name of the ufunc, its arguments
and its domain), the context is processed and entries of the output masked array are masked wherever the corresponding
input fall outside the validity domain:
1.6.3 Examples
Lets consider a list of elements, x, where values of -9999. represent missing data. We wish to compute the average
value of the data and the vector of anomalies (deviations from the average):
Suppose now that we wish to print that same data, but with the missing values replaced by the average value.
Numerical operations
Numerical operations can be easily performed without worrying about missing values, dividing by zero, square roots
of negative numbers, etc.:
Four values of the output are invalid: the first one comes from taking the square root of a negative number, the second
from the division by zero, and the last two where the inputs were masked.
Lets consider an array d of random floats between 0 and 1. We wish to compute the average of the values of d while
ignoring any data outside the range [0.1, 0.9]:
In addition to the MaskedArray class, the numpy.ma module defines several constants.
masked
The masked constant is a special case of MaskedArray, with a float datatype and a null shape. It is used to
test whether a specific entry of a masked array is masked, or to mask one or several entries of a masked array:
nomask
Value indicating that a masked array has no invalid entry. nomask is used internally to speed up computations
when the mask is not needed.
masked_print_options
String used in lieu of missing data when a masked array is printed. By default, this string is --.
class MaskedArray()
A boolean mask with the same shape as the data, where a True value indicates that the corresponding element
of the data is invalid. The special value nomask is also acceptable for arrays without named fields, and indicates
that no data is invalid.
A fill_value, a value that may be used to replace the invalid entries in order to return a standard
numpy.ndarray.
See Also:
Array Attributes
data
Returns the underlying data, as a view of the masked array. If the underlying data is a subclass of
numpy.ndarray, it is returned as such.
The type of the data can be accessed through the baseclass attribute.
mask
Returns the underlying mask, as an array with the same shape and structure as the data, but where all fields are
atomically booleans. A value of True indicates an invalid entry.
recordmask
Returns the mask of the array if it has no named fields. For structured arrays, returns a ndarray of booleans
where entries are True if all the fields are masked, False otherwise:
>>> x = ma.array([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)],
... mask=[(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)],
... dtype=[(a, int), (b, int)])
>>> x.recordmask
array([False, False, True, False, False], dtype=bool)
fill_value
Returns the value used to fill the invalid entries of a masked array. The value is either a scalar (if the masked
array has no named fields), or a 0-D ndarray with the same dtype as the masked array if it has named fields.
The default filling value depends on the datatype of the array:
datatype default
bool True
int 999999
float 1.e20
complex 1.e20+0j
object ?
string N/A
baseclass
Returns the class of the underlying data.
sharedmask
Returns whether the mask of the array is shared between several masked arrays. If this is the case, any modifi-
cation to the mask of one array will be propagated to the others.
hardmask
Returns whether the mask is hard (True) or soft (False). When the mask is hard, masked entries cannot be
unmasked.
As MaskedArray is a subclass of ndarray, a masked array also inherits all the attributes and properties of a
ndarray instance.
MaskedArray.base Base object if memory is from some other object.
MaskedArray.ctypes An object to simplify the interaction of the array with the ctypes
module.
MaskedArray.dtype Data-type of the arrays elements.
MaskedArray.flags Information about the memory layout of the array.
MaskedArray.itemsize Length of one array element in bytes.
MaskedArray.nbytes Total bytes consumed by the elements of the array.
MaskedArray.ndim Number of array dimensions.
MaskedArray.shape Tuple of array dimensions.
MaskedArray.size Number of elements in the array.
MaskedArray.strides Tuple of bytes to step in each dimension when traversing an array.
MaskedArray.imag Imaginary part.
MaskedArray.real Real part
MaskedArray.flat Flat version of the array.
MaskedArray.__array_priority__
base
Base object if memory is from some other object.
Examples
The base of an array that owns its memory is None:
>>> x = np.array([1,2,3,4])
>>> x.base is None
True
>>> y = x[2:]
>>> y.base is x
True
ctypes
An object to simplify the interaction of the array with the ctypes module.
This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes
module. The returned object has, among others, data, shape, and strides attributes (see Notes below) which
themselves return ctypes objects that can be used as arguments to a shared library.
Parameters
None :
Returns
c : Python object
Possessing attributes data, shape, strides, etc.
See Also:
numpy.ctypeslib
Notes
Below are the public attributes of this object which were documented in Guide to NumPy (we have omitted
undocumented public attributes, as well as documented private attributes):
data: A pointer to the memory area of the array as a Python integer. This memory area may contain data
that is not aligned, or not in correct byte-order. The memory area may not even be writeable. The array
flags and data-type of this array should be respected when passing this attribute to arbitrary C-code to avoid
trouble that can include Python crashing. User Beware! The value of this attribute is exactly the same as
self._array_interface_[data][0].
shape (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the C-integer corre-
sponding to dtype(p) on this platform. This base-type could be c_int, c_long, or c_longlong depending
on the platform. The c_intp type is defined accordingly in numpy.ctypeslib. The ctypes array contains the
shape of the underlying array.
strides (c_intp*self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the
shape attribute. This ctypes array contains the strides information from the underlying array. This strides
information is important for showing how many bytes must be jumped to get to the next element in the
array.
data_as(obj): Return the data pointer cast to a particular c-types object. For example, calling
self._as_parameter_ is equivalent to self.data_as(ctypes.c_void_p). Perhaps you want to use the data as
a pointer to a ctypes array of floating-point data: self.data_as(ctypes.POINTER(ctypes.c_double)).
shape_as(obj): Return the shape tuple as an array of some other c-types type. For example:
self.shape_as(ctypes.c_short).
strides_as(obj): Return the strides tuple as an array of some other c-types type. For example:
self.strides_as(ctypes.c_longlong).
Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For
example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that is
invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this
problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array
until ct is deleted or re-assigned.
If the ctypes module is not available, then the ctypes attribute of array objects still returns something useful, but
ctypes objects are not returned and errors may be raised instead. In particular, the object will still have the as
parameter attribute which will return an integer equal to the data attribute.
Examples
dtype
Data-type of the arrays elements.
Parameters
None :
Returns
d : numpy dtype object
See Also:
numpy.dtype
Examples
>>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype(int32)
>>> type(x.dtype)
<type numpy.dtype>
flags
Information about the memory layout of the array.
Notes
The flags object can be accessed dictionary-like (as in a.flags[WRITEABLE]), or by using lowercased
attribute names (as in a.flags.writeable). Short flag names are only supported in dictionary access.
Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by the user, via direct assign-
ment to the attribute or dictionary entry, or by calling ndarray.setflags.
The array flags cannot be set arbitrarily:
UPDATEIFCOPY can only be set False.
ALIGNED can only be set True if the data is truly aligned.
WRITEABLE can only be set True if the array owns its own memory or the ultimate owner of the memory
exposes a writeable buffer interface or is a string.
Attributes
itemsize
Length of one array element in bytes.
Examples
nbytes
Total bytes consumed by the elements of the array.
Notes
Does not include memory consumed by non-element attributes of the array object.
Examples
ndim
Number of array dimensions.
Examples
shape
Tuple of array dimensions.
Notes
May be used to reshape the array, as long as this would not require a change in the total number of elements
Examples
size
Number of elements in the array.
Examples
strides
Tuple of bytes to step in each dimension when traversing an array.
The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:
A more detailed explanation of strides can be found in the ndarray.rst file in the NumPy reference guide.
See Also:
numpy.lib.stride_tricks.as_strided
Notes
Imagine an array of 32-bit integers (each 4 bytes):
x = np.array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]], dtype=np.int32)
This array is stored in memory as 40 bytes, one after the other (known as a contiguous block of memory). The
strides of an array tell us how many bytes we have to skip in memory to move to the next position along a certain
axis. For example, we have to skip 4 bytes (1 value) to move to the next column, but 20 bytes (5 values) to get
to the same position in the next row. As such, the strides for the array x will be (20, 4).
Examples
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813
imag
Imaginary part.
real
Real part
flat
Flat version of the array.
See Also:
Array methods
Conversion
__int__()
Convert to int.
__long__() <==> long(x)
view(dtype=None, type=None)
New view of array with the same data.
Parameters
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
type : python type
Type of the returned view, e.g. ndarray or matrix.
Notes
a.view() is used two different ways.
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the arrays memory with a different
dtype. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass), or a.view(type=ndarray_subclass), just returns an instance of ndarray_subclass that
looks at the same array (same shape, dtype, etc.). This does not cause a reinterpretation of the memory.
Examples
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
astype(newtype)
Returns a copy of the MaskedArray cast to given newtype.
Returns
output : MaskedArray
A copy of self cast to input newtype. The returned record shape matches self.shape.
Examples
byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally
swapped in-place.
Parameters
inplace: bool, optional :
If True, swap bytes in-place, default is False.
Returns
out: ndarray :
The byteswapped array. If inplace is True, this is a view to self.
Examples
compressed()
Return all the non-masked data as a 1-D array.
Returns
data : ndarray
A new ndarray holding the non-masked data is returned.
Notes
The result is not a MaskedArray!
Examples
filled(fill_value=None)
Return a copy of self, with masked values filled with a given value.
Parameters
fill_value : scalar, optional
The value to use for invalid entries (None by default). If None, the fill_value attribute
of the array is used instead.
Notes
The result is not a MaskedArray!
Examples
Subclassing is preserved. This means that if the data part of the masked array is a matrix, filled returns a matrix:
Raises
NotImplementedError :
When tofile is called.
toflex()
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
Parameters
None :
Returns
record : ndarray
A new flexible-type ndarray with two fields: the first element containing a value, the
second element containing the corresponding mask boolean. The returned record shape
matches self.shape.
Notes
A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value,
...) will be lost.
Examples
tolist(fill_value=None)
Return the data portion of the masked array as a hierarchical Python list.
Data items are converted to the nearest compatible Python type. Masked values are converted to fill_value. If
fill_value is None, the corresponding entries in the output list will be None.
Parameters
fill_value : scalar, optional
The value to use for invalid entries. Default is None.
Returns
result : list
The Python list representation of the masked array.
Examples
torecords()
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
the _data field stores the _data part of the array.
Parameters
None :
Returns
record : ndarray
A new flexible-type ndarray with two fields: the first element containing a value, the
second element containing the corresponding mask boolean. The returned record shape
matches self.shape.
Notes
A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value,
...) will be lost.
Examples
tostring(fill_value=None, order=C)
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
Parameters
fill_value : scalar, optional
Value used to fill in the masked values. Deafult is None, in which case MaskedAr-
ray.fill_value is used.
order : {C,F,A}, optional
Order of the data item in the copy. Default is C.
C C order (row major).
F Fortran order (column major).
A Any, current order of array.
None Same as A.
See Also:
ndarray.tostring, tolist, tofile
Notes
As for ndarray.tostring, information about the shape, dtype, etc., but also about fill_value, will be lost.
Examples
Shape manipulation
For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted
as an n-tuple.
MaskedArray.flatten([order]) Return a copy of the array collapsed into one dimension.
MaskedArray.ravel() Returns a 1D version of self, as a view.
MaskedArray.reshape(*s, **kwargs) Give a new shape to the array without changing its data.
MaskedArray.resize(newshape[, refcheck,
order])
MaskedArray.squeeze() Remove single-dimensional entries from the shape of a.
MaskedArray.swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2
interchanged.
MaskedArray.transpose(*axes) Returns a view of the array with axes transposed.
MaskedArray.T
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is
C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
ravel()
Returns a 1D version of self, as a view.
Returns
MaskedArray :
Examples
reshape(*s, **kwargs)
Give a new shape to the array without changing its data.
Returns a masked array containing the same data, but with a new shape. The result is a view on the original
array; if this is not possible, a ValueError is raised.
Parameters
shape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer is supplied,
then the result will be a 1-D array of that length.
order : {C, F}, optional
Determines whether the array data should be viewed as in C (row-major) or FORTRAN
(column-major) order.
Returns
reshaped_array : array
A new view on the array.
See Also:
reshape
Equivalent function in the masked array module.
numpy.ndarray.reshape
Equivalent method on ndarray object.
numpy.reshape
Equivalent function in the NumPy module.
Notes
The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use
a.shape = s
Examples
[3]
[--]]
This method is difficult to implement safely and may be deprecated in future releases of NumPy.
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a ma-
trix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order in-
dicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1],
... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1],
i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s j-th
axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
For array methods that take an axis keyword, it defaults to None. If axis is None, then the array is treated as a 1-D
array. Any other value for axis represents the dimension along which the operation should proceed.
MaskedArray.argmax([axis, fill_value, Returns array of indices of the maximum values along the given
out]) axis.
MaskedArray.argmin([axis, fill_value, Return array of indices to the minimum values along the given
out]) axis.
MaskedArray.argsort([axis, kind, Return an ndarray of indices that sort the array along the
order, ...]) specified axis.
MaskedArray.choose(choices[, out, Use an index array to construct a new array from a set of choices.
mode])
MaskedArray.compress(condition[, Return a where condition is True.
axis, out])
MaskedArray.diagonal([offset, axis1, Return specified diagonals.
axis2])
MaskedArray.fill(value) Fill the array with a scalar value.
MaskedArray.item(*args) Copy an element of an array to a standard Python scalar and
return it.
MaskedArray.nonzero() Return the indices of unmasked elements that are not zero.
MaskedArray.put(indices, values[, Set storage-indexed locations to corresponding values.
mode])
MaskedArray.repeat(repeats[, axis]) Repeat elements of an array.
MaskedArray.searchsorted(v[, side]) Find indices where elements of v should be inserted in a to
maintain order.
MaskedArray.sort([axis, kind, order, Sort the array, in-place
...])
MaskedArray.take(indices[, axis, out,
mode])
argmax(axis=None, fill_value=None, out=None)
Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had
the value fill_value.
Parameters
axis : {None, integer}
If None, the index is into the flattened array, otherwise along the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of maxi-
mum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
Returns
index_array : {integer_array}
Examples
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
Examples
sort
Describes sorting algorithms used.
lexsort
Indirect stable sort with multiple keys.
ndarray.sort
Inplace sort.
Notes
See sort for notes on the different sorting algorithms.
Examples
numpy.choose
equivalent function
Notes
Please note the difference with compressed ! The output of compress has a mask, the output of
compressed does not.
Examples
See Also:
numpy.diagonal
equivalent function
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which element
to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument is
interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is no
available Python scalar that would not lose information. Void arrays return a buffer object for item(), unless
fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This can
be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using
Pythons optimized math.
Examples
[8, 5, 3]])
>>> x.item(3)
2
>>> x.item(7)
5
>>> x.item((0, 1))
1
>>> x.item((2, 2))
3
nonzero()
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[a.nonzero()]
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero element.
Parameters
None :
Returns
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also:
numpy.nonzero
Function operating on ndarrays.
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(data =
[[False False False]
[ True True True]
[ True True True]],
mask =
False,
fill_value=999999)
>>> ma.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
Specifies how out-of-bounds indices will behave. raise : raise an error. wrap : wrap
around. clip : clip to the range.
Notes
values can be a scalar or length 1 array.
Examples
>>> x.put(4,999)
>>> print x
[[10 -- 3]
[-- 999 --]
[7 -- 30]]
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
searchsorted(v, side=left)
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see numpy.searchsorted
See Also:
numpy.searchsorted
equivalent function
ndarray.sort
Method to sort an array in-place.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in a sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an array.
Parameters
None :
Calculations
all
equivalent function
Examples
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
anom(axis=None, dtype=None)
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
any(axis=None, out=None)
Check if any of the elements of a are true.
Performs a logical_or over the given axis and returns the result. Masked values are considered as False during
computation.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array and return a
scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
any
equivalent function
numpy.clip
equivalent function
conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
conjugate()
Return the complex conjugate, element-wise.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis. The cumulative sum is calculated over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array. axis may be negative, in which case it counts from the last to the
first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the elements are summed. If
dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a
precision less than that of the default platform integer. In that case, the default platform
integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumsum : ndarray.
A new array holding the result is returned unless out is specified, in which case a
reference to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
Value used to fill in the masked values. If None, use the output of maxi-
mum_fill_value().
Returns
amax : array_like
New array holding the result. If out was specified, out is returned.
See Also:
maximum_fill_value
Returns the maximum filling value for a given datatype.
numpy.ma.mean
Equivalent function.
numpy.mean
Equivalent function on non-masked arrays.
numpy.ma.average
Weighted average.
Examples
minimum_fill_value
Returns the minimum filling value for a given datatype.
prod
equivalent function
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
prod
equivalent function
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> np.prod([1.,2.])
2.0
numpy.around
equivalent function
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type (of the calculated values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements. By default ddof is zero.
Returns
standard_deviation : ndarray, see dtype parameter above.
If out is None, return a new array containing the standard deviation, otherwise return a
reference to the output array.
See Also:
var, mean
numpy.doc.ufuncs
Section Output arguments
Notes
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =
sqrt(mean(abs(x - x.mean())**2)).
The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however,
ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate
of the variance for normally distributed variables. The standard deviation computed in this function is the
square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard
deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real
and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input
data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-
accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
Examples
numpy.trace
equivalent function
Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed
for the flattened array by default, otherwise over the specified axis.
Parameters
a : array_like
Array containing numbers whose variance is desired. If a is not an array, a conversion
is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type the default is float32;
for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type is cast if necessary.
ddof : int, optional
Delta Degrees of Freedom: the divisor used in calculation is N - ddof, where N
represents the number of elements. By default ddof is zero.
Returns
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise a reference to the
output array is returned.
See Also:
std
Standard deviation
mean
Average
numpy.doc.ufuncs
Section Output arguments
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x -
x.mean())**2).
The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the
divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of
the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for
normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and
nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the
input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a
higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
Comparison operators:
MaskedArray.__lt__ x.__lt__(y) <==> x<y
MaskedArray.__le__ x.__le__(y) <==> x<=y
MaskedArray.__gt__ x.__gt__(y) <==> x>y
MaskedArray.__ge__ x.__ge__(y) <==> x>=y
MaskedArray.__eq__(other) Check whether other equals self elementwise
MaskedArray.__ne__(other) Check whether other doesnt equal self elementwise
__lt__()
x.__lt__(y) <==> x<y
__le__()
x.__le__(y) <==> x<=y
__gt__()
x.__gt__(y) <==> x>y
__ge__()
x.__ge__(y) <==> x>=y
__eq__(other)
Check whether other equals self elementwise
__ne__(other)
Check whether other doesnt equal self elementwise
__nonzero__()
x.__nonzero__() <==> x != 0
Arithmetic:
MaskedArray.__abs__(x)
MaskedArray.__add__(other) Add other to self, and return a new masked array.
MaskedArray.__radd__(other) Add other to self, and return a new masked array.
MaskedArray.__sub__(other) Subtract other to self, and return a new masked array.
MaskedArray.__rsub__(other) Subtract other to self, and return a new masked array.
MaskedArray.__mul__(other) Multiply other by self, and return a new masked array.
MaskedArray.__rmul__(other) Multiply other by self, and return a new masked array.
MaskedArray.__div__(other) Divide other into self, and return a new masked array.
MaskedArray.__rdiv__ x.__rdiv__(y) <==> y/x
MaskedArray.__truediv__(other) Divide other into self, and return a new masked array.
MaskedArray.__rtruediv__(other) Divide other into self, and return a new masked array.
MaskedArray.__floordiv__(other) Divide other into self, and return a new masked array.
MaskedArray.__rfloordiv__(other) Divide other into self, and return a new masked array.
MaskedArray.__mod__ x.__mod__(y) <==> x%y
MaskedArray.__rmod__ x.__rmod__(y) <==> y%x
MaskedArray.__divmod__(x, y)
MaskedArray.__rdivmod__(y, x)
MaskedArray.__pow__(other) Raise self to the power other, masking the potential NaNs/Infs
MaskedArray.__rpow__(other) Raise self to the power other, masking the potential NaNs/Infs
MaskedArray.__lshift__ x.__lshift__(y) <==> x<<y
MaskedArray.__rlshift__ x.__rlshift__(y) <==> y<<x
MaskedArray.__rshift__ x.__rshift__(y) <==> x>>y
MaskedArray.__rrshift__ x.__rrshift__(y) <==> y>>x
MaskedArray.__and__ x.__and__(y) <==> x&y
MaskedArray.__rand__ x.__rand__(y) <==> y&x
MaskedArray.__or__ x.__or__(y) <==> x|y
MaskedArray.__ror__ x.__ror__(y) <==> y|x
MaskedArray.__xor__ x.__xor__(y) <==> x^y
MaskedArray.__rxor__ x.__rxor__(y) <==> y^x
__abs__() <==> abs(x)
__add__(other)
Add other to self, and return a new masked array.
__radd__(other)
Add other to self, and return a new masked array.
__sub__(other)
Subtract other to self, and return a new masked array.
__rsub__(other)
Subtract other to self, and return a new masked array.
__mul__(other)
Multiply other by self, and return a new masked array.
__rmul__(other)
Multiply other by self, and return a new masked array.
__div__(other)
Divide other into self, and return a new masked array.
__rdiv__()
x.__rdiv__(y) <==> y/x
__truediv__(other)
Divide other into self, and return a new masked array.
__rtruediv__(other)
Divide other into self, and return a new masked array.
__floordiv__(other)
Divide other into self, and return a new masked array.
__rfloordiv__(other)
Divide other into self, and return a new masked array.
__mod__()
x.__mod__(y) <==> x%y
__rmod__()
x.__rmod__(y) <==> y%x
__divmod__(y) <==> divmod(x, y)
__pow__(other)
Raise self to the power other, masking the potential NaNs/Infs
__rpow__(other)
Raise self to the power other, masking the potential NaNs/Infs
__lshift__()
x.__lshift__(y) <==> x<<y
__rlshift__()
x.__rlshift__(y) <==> y<<x
__rshift__()
x.__rshift__(y) <==> x>>y
__rrshift__()
x.__rrshift__(y) <==> y>>x
__and__()
x.__and__(y) <==> x&y
__rand__()
x.__rand__(y) <==> y&x
__or__()
x.__or__(y) <==> x|y
__ror__()
x.__ror__(y) <==> y|x
__xor__()
x.__xor__(y) <==> x^y
__rxor__()
x.__rxor__(y) <==> y^x
Arithmetic, in-place:
MaskedArray.__iadd__(other) Add other to self in-place.
MaskedArray.__isub__(other) Subtract other from self in-place.
MaskedArray.__imul__(other) Multiply self by other in-place.
MaskedArray.__idiv__(other) Divide self by other in-place.
MaskedArray.__itruediv__(other) True divide self by other in-place.
MaskedArray.__ifloordiv__(other) Floor divide self by other in-place.
MaskedArray.__imod__ x.__imod__(y) <==> x%y
MaskedArray.__ipow__(other) Raise self to the power other, in place.
MaskedArray.__ilshift__ x.__ilshift__(y) <==> x<<y
MaskedArray.__irshift__ x.__irshift__(y) <==> x>>y
MaskedArray.__iand__ x.__iand__(y) <==> x&y
MaskedArray.__ior__ x.__ior__(y) <==> x|y
MaskedArray.__ixor__ x.__ixor__(y) <==> x^y
__iadd__(other)
Add other to self in-place.
__isub__(other)
Subtract other from self in-place.
__imul__(other)
Multiply self by other in-place.
__idiv__(other)
Divide self by other in-place.
__itruediv__(other)
True divide self by other in-place.
__ifloordiv__(other)
Floor divide self by other in-place.
__imod__()
x.__imod__(y) <==> x%y
__ipow__(other)
Raise self to the power other, in place.
__ilshift__()
x.__ilshift__(y) <==> x<<y
__irshift__()
x.__irshift__(y) <==> x>>y
__iand__()
x.__iand__(y) <==> x&y
__ior__()
x.__ior__(y) <==> x|y
__ixor__()
x.__ixor__(y) <==> x^y
Representation
Examples
If the array has no mask, the address of nomask is returned. This address is typically not close to the data in
memory:
iscontiguous()
Return a boolean indicating whether the data is contiguous.
Parameters
None :
Examples
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
Special methods
__getstate__()
Return the internal state of the masked array, for pickling purposes.
__reduce__()
Return a 3-tuple for pickling a MaskedArray.
__setstate__(state)
Restore the internal state of the masked array, for pickling purposes. state is typically the output of the
__getstate__ output, and is a 5-tuple:
class name
a tuple giving the shape of the data
a typecode for the data
a binary string for the data
a binary string for the mask.
Basic customization:
MaskedArray.__new__
MaskedArray.__array__ a.__array__(|dtype) -> reference if type unchanged, copy
otherwise.
MaskedArray.__array_wrap__(obj[, Special hook for ufuncs.
context])
__array__()
a.__array__(|dtype) -> reference if type unchanged, copy otherwise.
Returns either a new reference to self if dtype is not given or a new array of provided data type if dtype is
different from the current dtype of the array.
__array_wrap__(obj, context=None)
Special hook for ufuncs. Wraps the numpy array and sets the mask according to context.
Container customization: (see Indexing)
MaskedArray.__len__(x)
MaskedArray.__getitem__(indx) x.__getitem__(y) <==> x[y]
MaskedArray.__setitem__(indx, value) x.__setitem__(i, y) <==> x[i]=y
MaskedArray.__delitem__ x.__delitem__(y) <==> del x[y]
MaskedArray.__getslice__(i, j) x.__getslice__(i, j) <==> x[i:j]
MaskedArray.__setslice__(i, j, value) x.__setslice__(i, j, value) <==> x[i:j]=value
MaskedArray.__contains__ x.__contains__(y) <==> y in x
__len__() <==> len(x)
__getitem__(indx)
x.__getitem__(y) <==> x[y]
Return the item described by i, as a masked array.
__setitem__(indx, value)
x.__setitem__(i, y) <==> x[i]=y
Set item described by index. If value is masked, masks those locations.
__delitem__()
x.__delitem__(y) <==> del x[y]
__getslice__(i, j)
x.__getslice__(i, j) <==> x[i:j]
Return the slice described by (i, j). The use of negative indices is not supported.
__setslice__(i, j, value)
x.__setslice__(i, j, value) <==> x[i:j]=value
Set the slice (i,j) of a to value. If value is masked, mask those locations.
__contains__()
x.__contains__(y) <==> y in x
Specific methods
soften_mask()
Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by its hardmask property. soften_mask sets
hardmask to False.
See Also:
hardmask
unshare_mask()
Copy the mask and set the sharedmask flag to False.
Whether the mask is shared between masked arrays can be seen from the sharedmask property. unshare_mask
ensures the mask is not shared. A copy of the mask is only made if it was shared.
See Also:
sharedmask
shrink_mask()
Reduce a mask to nomask when possible.
Parameters
None :
Returns
None :
Examples
Examples
set_fill_value(value=None)
Set the filling value of the masked array.
Parameters
value : scalar, optional
The new filling value. Default is None, in which case a default based on the data type
is used.
See Also:
ma.set_fill_value
Equivalent function.
Examples
Reset to default:
>>> x.set_fill_value()
>>> x.fill_value
1e+20
count_masked
Count masked elements in array or along a given axis.
Examples
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
Constants
Creation
Parameters
data : array_like
Input data.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same shape as data. True
indicates a masked (i.e. invalid) data.
dtype : dtype, optional
Data type of the output. If dtype is None, the type of the data argument (data.dtype)
is used. If dtype is not None and different from data.dtype, a copy is performed.
copy : bool, optional
Whether to copy the input data (True), or to use a reference instead. Default is False.
subok : bool, optional
Whether to return a subclass of MaskedArray if possible (True) or a plain MaskedArray.
Default is True.
ndmin : int, optional
Minimum number of dimensions. Default is 0.
fill_value : scalar, optional
Value used to fill in the masked values when necessary. If None, a default based on the
data-type is used.
keep_mask : bool, optional
Whether to combine mask with the mask of the input data, if any (True), or to use only
mask for the output (False). Default is True.
hard_mask : bool, optional
Whether to use a hard mask or not. With a hard mask, masked values cannot be un-
masked. Default is False.
shrink : bool, optional
Whether to force compression of an empty mask. Default is True.
copy
copy a.copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
frombuffer
Interpret a buffer as a 1-dimensional array.
Parameters
buffer :
An object that exposes the buffer interface.
dtype : data-type, optional
Data type of the returned array.
count : int, optional
Number of items to read. -1 means all data in the buffer.
offset : int, optional
Start reading the buffer from this offset.
Notes
If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.:
>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder(>)
>>> np.frombuffer(buf, dtype=dt)
The data of the resulting array will not be byteswapped, but will be interpreted correctly.
Examples
fromfunction
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).
Parameters
function : callable
The function is called with N parameters, each of which represents the coordinates of
the array varying along a specific axis. For example, if shape were (2, 2), then the
parameters would be two arrays, [[0, 0], [1, 1]] and [[0, 1], [0, 1]].
function must be capable of operating on arrays, and should return a scalar value.
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of the coordinate arrays
passed to function.
dtype : data-type, optional
Data-type of the coordinate arrays passed to function. By default, dtype is float.
Returns
out : any
The result of the call to function is passed back directly. Therefore the type and shape
of out is completely determined by function.
See Also:
indices, meshgrid
Notes
Keywords other than shape and dtype are passed to function.
Examples
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
Notes
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other
hand, it requires the user to manually set all the values in the array, and should be used with caution.
Examples
empty_like
Return a new array with the same shape and type as a given array.
Parameters
a : array_like
The shape and data-type of a define the parameters of the returned array.
Returns
out : ndarray
Array of random data with the same shape and type as a.
See Also:
ones_like
Return an array of ones with shape and type of input.
zeros_like
Return an array of zeros with shape and type of input.
empty
Return a new uninitialized array.
ones
Return a new array setting values to one.
zeros
Return a new array setting values to zero.
Notes
This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be
marginally faster than the functions that do set the array values.
Examples
Parameters
shape : tuple
Shape of the required MaskedArray.
dtype : dtype, optional
Data type of the output.
Returns
a : MaskedArray
A masked array with all data masked.
See Also:
masked_all_like
Empty masked array modelled on an existing array.
Examples
masked_all_like(arr)
Empty masked array with the properties of an existing array.
Return an empty masked array of the same shape and dtype as the array arr, where all the data are masked.
Parameters
arr : ndarray
An array describing the shape and dtype of the required MaskedArray.
Returns
a : MaskedArray
A masked array with all data masked.
Raises
AttributeError :
If arr doesnt have a shape attribute (i.e. not an ndarray)
See Also:
masked_all
Empty masked array with all elements masked.
Examples
>>> arr.dtype
dtype(float32)
>>> ma.masked_all_like(arr).dtype
dtype(float32)
ones
Return a new array of given shape and type, filled with ones.
Please refer to the documentation for zeros.
See Also:
zeros
Examples
>>> np.ones(5)
array([ 1., 1., 1., 1., 1.])
>>> s = (2,2)
>>> np.ones(s)
array([[ 1., 1.],
[ 1., 1.]])
zeros
Return a new array of given shape and type, filled with zeros.
Parameters
shape : int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.
dtype : data-type, optional
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
order : {C, F}, optional
Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-
wise) order in memory.
Returns
out : ndarray
Array of zeros with the given shape, dtype, and order.
See Also:
zeros_like
Return an array of zeros with shape and type of input.
ones_like
Return an array of ones with shape and type of input.
empty_like
Return an empty array with shape and type of input.
ones
Return a new array setting values to one.
empty
Return a new uninitialized array.
Examples
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
all
equivalent function
Examples
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
any
Check if any of the elements of a are true.
Performs a logical_or over the given axis and returns the result. Masked values are considered as False during
computation.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array and return a
scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
any
equivalent function
count(a, axis=None)
Count the non-masked elements of the array along the given axis.
Parameters
axis : int, optional
Axis along which to count the non-masked elements. If axis is None, all non-masked
elements are counted.
Returns
result : int or ndarray
If axis is None, an integer count is returned. When axis is not None, an array with shape
determined by the lengths of the remaining axes, is returned.
See Also:
count_masked
Count masked elements in array or along a given axis.
Examples
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
count_masked(arr, axis=None)
Count the number of masked elements along the given axis.
Parameters
arr : array_like
An array with (possibly) masked elements.
axis : int, optional
Axis along which to count. If None (default), a flattened version of the array is used.
Returns
count : int, ndarray
The total number of masked elements (axis=None) or the number of masked elements
along each slice of the given axis.
See Also:
MaskedArray.count
Count non-masked elements.
Examples
getmask(a)
Return the mask of a masked array, or nomask.
Return the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask, else return nomask. To
guarantee a full array of booleans of the same shape as a, use getmaskarray.
Parameters
a : array_like
Input MaskedArray for which the mask is required.
See Also:
getdata
Return the data of a masked array as an ndarray.
getmaskarray
Return the mask of a masked array, or full array of False.
Examples
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
getmaskarray(arr)
Return the mask of a masked array, or full boolean array of False.
Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask, else return a full
boolean array of False of the same shape as arr.
Parameters
arr : array_like
Input MaskedArray for which the mask is required.
See Also:
getmask
Return the mask of a masked array, or nomask.
getdata
Return the data of a masked array as an ndarray.
Examples
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> >ma.getmaskarray(b)
array([[False, False],
[False, False]], dtype=bool)
getdata(a, subok=True)
Return the data of a masked array as an ndarray.
Return the data of a (if any) as an ndarray if a is a MaskedArray, else return a as a ndarray or subclass
(depending on subok) if not.
Parameters
a : array_like
Input MaskedArray, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a pure ndarray (False) or to return a subclass of ndarray
if appropriate (True, default).
See Also:
getmask
Return the mask of a masked array, or nomask.
getmaskarray
Return the mask of a masked array, or full array of False.
Examples
>>> a.data
array([[1, 2],
[3, 4]])
nonzero
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[a.nonzero()]
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero element.
Parameters
None :
Returns
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also:
numpy.nonzero
Function operating on ndarrays.
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(data =
[[False False False]
[ True True True]
[ True True True]],
mask =
False,
fill_value=999999)
>>> ma.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
shape(obj)
Return the shape of an array.
Parameters
a : array_like
Input array.
Returns
shape : tuple of ints
The elements of the shape tuple give the lengths of the corresponding array dimensions.
See Also:
alen
ndarray.shape
Equivalent array method.
Examples
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
size(obj, axis=None)
Return the number of elements along a given axis.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give the total number of ele-
ments.
Returns
element_count : int
Number of elements along the specified axis.
See Also:
shape
dimensions of array
ndarray.shape
dimensions of array
ndarray.size
number of elements in array
Examples
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
data
mask
Mask
recordmask
all(axis=None, out=None)
Check if all of the elements of a are true.
Performs a logical_and over the given axis and returns the result. Masked values are considered as True
during computation. For convenience, the output array is masked where ALL the values along the current axis
are masked: if the output would have been a scalar and that all the values are masked, then the output is masked.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
all
equivalent function
Examples
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
any(axis=None, out=None)
Check if any of the elements of a are true.
Performs a logical_or over the given axis and returns the result. Masked values are considered as False during
computation.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array and return a
scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
any
equivalent function
count(axis=None)
Count the non-masked elements of the array along the given axis.
Parameters
axis : int, optional
Axis along which to count the non-masked elements. If axis is None, all non-masked
elements are counted.
Returns
result : int or ndarray
If axis is None, an integer count is returned. When axis is not None, an array with shape
determined by the lengths of the remaining axes, is returned.
See Also:
count_masked
Count masked elements in array or along a given axis.
Examples
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
nonzero()
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[a.nonzero()]
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero element.
Parameters
None :
Returns
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also:
numpy.nonzero
Function operating on ndarrays.
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
>>> x.nonzero()
(array([0, 2]), array([0, 2]))
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(data =
[[False False False]
[ True True True]
[ True True True]],
mask =
False,
fill_value=999999)
>>> ma.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
shape(obj)
Return the shape of an array.
Parameters
a : array_like
Input array.
Returns
shape : tuple of ints
The elements of the shape tuple give the lengths of the corresponding array dimensions.
See Also:
alen
ndarray.shape
Equivalent array method.
Examples
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
size(obj, axis=None)
Return the number of elements along a given axis.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give the total number of ele-
ments.
Returns
element_count : int
Number of elements along the specified axis.
See Also:
shape
dimensions of array
ndarray.shape
dimensions of array
ndarray.size
number of elements in array
Examples
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
Manipulating a MaskedArray
Examples
MaskedArray.reshape
equivalent function
resize(x, new_shape)
Return a new masked array with the specified size and shape.
This is the masked equivalent of the numpy.resize function. The new array is filled with repeated copies of
x (in the order that the data are stored in memory). If x is masked, the new array will be masked, and the new
mask will be a repetition of the old one.
See Also:
numpy.resize
Equivalent function in the top level NumPy module.
Examples
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is
C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
ravel()
Returns a 1D version of self, as a view.
Returns
MaskedArray :
Output view is of shape (self.size,) (or
(np.ma.product(self.shape),)).
Examples
reshape(*s, **kwargs)
Give a new shape to the array without changing its data.
Returns a masked array containing the same data, but with a new shape. The result is a view on the original
array; if this is not possible, a ValueError is raised.
Parameters
shape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer is supplied,
then the result will be a 1-D array of that length.
order : {C, F}, optional
Determines whether the array data should be viewed as in C (row-major) or FORTRAN
(column-major) order.
Returns
reshaped_array : array
A new view on the array.
See Also:
reshape
Equivalent function in the masked array module.
numpy.ndarray.reshape
Equivalent method on ndarray object.
numpy.reshape
Equivalent function in the NumPy module.
Notes
The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use
a.shape = s
Examples
This method is difficult to implement safely and may be deprecated in future releases of NumPy.
Modifying axes
ma.swapaxes swapaxes
ma.transpose(a[, axes]) Permute the dimensions of an array.
ma.MaskedArray.swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged.
ma.MaskedArray.transpose(*axes) Returns a view of the array with axes transposed.
swapaxes
swapaxes a.swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
transpose(a, axes=None)
Permute the dimensions of an array.
This function is exactly equivalent to numpy.transpose.
See Also:
numpy.transpose
Equivalent function in top-level NumPy module.
Examples
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a ma-
trix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order in-
dicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1],
... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1],
i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s j-th
axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
Examples
>>> np.atleast_1d(1.0)
array([ 1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
atleast_2d(*arys)
View inputs as arrays with at least two dimensions.
Parameters
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays
that already have two or more dimensions are preserved.
Returns
res, res2, ... : ndarray
An array, or tuple of arrays, each with a.ndim >= 2. Copies are avoided where
possible, and views with two or more dimensions are returned.
See Also:
atleast_1d, atleast_3d
Examples
>>> np.atleast_2d(3.0)
array([[ 3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[ 0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True
atleast_3d(*arys)
View inputs as arrays with at least three dimensions.
Parameters
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays
that already have three or more dimensions are preserved.
Returns
res1, res2, ... : ndarray
An array, or tuple of arrays, each with a.ndim >= 3. Copies are avoided where
possible, and views with three or more dimensions are returned. For example, a 1-D
array of shape N becomes a view of shape (1, N, 1). A 2-D array of shape (M, N)
becomes a view of shape (M, N, 1).
See Also:
atleast_1d, atleast_2d
Examples
>>> np.atleast_3d(3.0)
array([[[ 3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x
True
expand_dims(x, axis)
Expand the shape of an array.
Expands the shape of the array by including a new axis before the one specified by the axis parameter. This
function behaves the same as numpy.expand_dims but preserves masked elements.
See Also:
numpy.expand_dims
Equivalent function in top-level NumPy module.
Examples
array([[1, 2, 4]])
>>> ma.expand_dims(x, axis=0)
masked_array(data =
[[1 -- 4]],
mask =
[[False True False]],
fill_value = 999999)
The same result can be achieved using slicing syntax with np.newaxis.
>>> x[np.newaxis, :]
masked_array(data =
[[1 -- 4]],
mask =
[[False True False]],
fill_value = 999999)
squeeze(a)
Remove single-dimensional entries from the shape of an array.
Parameters
a : array_like
Input data.
Returns
squeezed : ndarray
The input array, but with with all dimensions of length 1 removed. Whenever possible,
a view on a is returned.
Examples
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
column_stack
Parameters
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
stacked : 2-D array
The array formed by stacking the given arrays.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
concatenate(arrays, axis=0)
Concatenate a sequence of arrays along the given axis.
Parameters
arrays : sequence of array_like
The arrays must have the same shape, except in the dimension corresponding to axis
(the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
result : MaskedArray
The concatenated array with any masked entries preserved.
See Also:
numpy.concatenate
Equivalent function in the top-level NumPy module.
Examples
dstack
Parameters
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all but the third axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack along first axis.
hstack
Stack along second axis.
concatenate
Join arrays.
dsplit
Split array along third axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
hstack
Parameters
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third axis).
concatenate
Join a sequence of arrays together.
hsplit
Split array along second axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
hsplit
split
Split an array into multiple sub-arrays of equal size.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[ 12., 13., 14.]]),
array([[ 3.],
[ 7.],
[ 11.],
[ 15.]]),
array([], dtype=float64)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0., 1.]],
[[ 4., 5.]]]),
array([[[ 2., 3.]],
[[ 6., 7.]]])]
mr_
Translate slice objects to concatenation along the first axis.
This is the masked array version of lib.index_tricks.RClass.
See Also:
lib.index_tricks.RClass
Examples
row_stack
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
vstack
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
Joining arrays
ma.column_stack(tup) Stack 1-D arrays as columns into a 2-D array.
ma.concatenate(arrays[, axis]) Concatenate a sequence of arrays along the given axis.
ma.dstack(tup) Stack arrays in sequence depth wise (along third axis).
ma.hstack(tup) Stack arrays in sequence horizontally (column wise).
ma.vstack(tup) Stack arrays in sequence vertically (row wise).
column_stack
Parameters
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
stacked : 2-D array
The array formed by stacking the given arrays.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
concatenate(arrays, axis=0)
Concatenate a sequence of arrays along the given axis.
Parameters
arrays : sequence of array_like
The arrays must have the same shape, except in the dimension corresponding to axis
(the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
result : MaskedArray
The concatenated array with any masked entries preserved.
See Also:
numpy.concatenate
Equivalent function in the top-level NumPy module.
Examples
masked_array(data = [0 -- 2],
mask = [False True False],
fill_value = 999999)
>>> b
masked_array(data = [2 3 4],
mask = False,
fill_value = 999999)
>>> ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
mask = [False True False False False False],
fill_value = 999999)
dstack
Parameters
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all but the third axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack along first axis.
hstack
Stack along second axis.
concatenate
Join arrays.
dsplit
Split array along third axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
hstack
Parameters
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third axis).
concatenate
Join a sequence of arrays together.
hsplit
Split array along second axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
vstack
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
Operations on masks
Creating a mask
ma.make_mask(m[, copy, shrink, flag, dtype]) Create a boolean mask from an array.
ma.make_mask_none(newshape[, dtype]) Return a boolean mask of the given shape, filled with False.
ma.mask_or(m1, m2[, copy, shrink]) Combine two masks with the logical_or operator.
ma.make_mask_descr(ndtype) Construct a dtype description list from a given dtype.
make_mask(m, copy=False, shrink=True, flag=None, dtype=<type numpy.bool_>)
Create a boolean mask from an array.
Return m as a boolean mask, creating a copy if necessary or requested. The function can accept any sequence
that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are
interepreted as False, everything else as True.
Parameters
m : array_like
Potential mask.
copy : bool, optional
Whether to return a copy of m (True) or m itself (False).
shrink : bool, optional
Whether to shrink m to nomask if all its values are False.
flag : bool, optional
Deprecated equivalent of shrink.
dtype : dtype, optional
Data-type of the output mask. By default, the output mask has a dtype of MaskType
(bool). If the dtype is flexible, each field has a boolean dtype.
Returns
result : ndarray
A boolean mask derived from m.
Examples
>>> m = np.zeros(4)
>>> m
array([ 0., 0., 0., 0.])
>>> ma.make_mask(m)
False
>>> ma.make_mask(m, shrink=False)
array([False, False, False, False], dtype=bool)
>>> m = [1, 0, 1, 1]
>>> n = [0, 1, 0, 0]
>>> arr = []
>>> for man, mouse in zip(m, n):
... arr.append((man, mouse))
>>> arr
[(1, 0), (0, 1), (1, 0), (1, 0)]
>>> dtype = np.dtype({names:[man, mouse],
formats:[np.int, np.int]})
>>> arr = np.array(arr, dtype=dtype)
>>> arr
array([(1, 0), (0, 1), (1, 0), (1, 0)],
dtype=[(man, <i4), (mouse, <i4)])
>>> ma.make_mask(arr, dtype=dtype)
array([(True, False), (False, True), (True, False), (True, False)],
dtype=[(man, |b1), (mouse, |b1)])
make_mask_none(newshape, dtype=None)
Return a boolean mask of the given shape, filled with False.
This function returns a boolean ndarray with all entries False, that can be used in common mask manipulations.
If a complex dtype is specified, the type of each field is converted to a boolean type.
Parameters
newshape : tuple
A tuple indicating the shape of the mask.
dtype: {None, dtype}, optional :
If None, use a MaskType instance. Otherwise, use a new datatype with the same fields
as dtype, converted to boolean types.
Returns
result : ndarray
An ndarray of appropriate shape and dtype, filled with False.
See Also:
make_mask
Create a boolean mask from an array.
make_mask_descr
Construct a dtype description list from a given dtype.
Examples
Examples
make_mask_descr(ndtype)
Construct a dtype description list from a given dtype.
Returns a new dtype object, with the type of all fields in ndtype to a boolean type. Field names are not altered.
Parameters
ndtype : dtype
The dtype to convert.
Returns
result : dtype
A dtype that looks like ndtype, the type of all fields is boolean.
Examples
Accessing a mask
ma.getmask(a) Return the mask of a masked array, or nomask.
ma.getmaskarray(arr) Return the mask of a masked array, or full boolean array of False.
ma.masked_array.mask Mask
getmask(a)
Return the mask of a masked array, or nomask.
Return the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask, else return nomask. To
guarantee a full array of booleans of the same shape as a, use getmaskarray.
Parameters
a : array_like
Input MaskedArray for which the mask is required.
See Also:
getdata
Return the data of a masked array as an ndarray.
getmaskarray
Return the mask of a masked array, or full array of False.
Examples
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
getmaskarray(arr)
Return the mask of a masked array, or full boolean array of False.
Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask, else return a full
boolean array of False of the same shape as arr.
Parameters
arr : array_like
Input MaskedArray for which the mask is required.
See Also:
getmask
Return the mask of a masked array, or nomask.
getdata
Return the data of a masked array as an ndarray.
Examples
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> >ma.getmaskarray(b)
array([[False, False],
[False, False]], dtype=bool)
mask
Mask
Notes
Only accepts 2-D arrays at most.
Examples
>>> a = np.arange(10)
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> ma = np.ma.array(a, mask=mask)
>>> np.array(ma[~ma.mask])
array([3, 4, 6, 7, 8])
>>> np.ma.extras.flatnotmasked_contiguous(ma)
[slice(3, 4, None), slice(6, 8, None)]
>>> ma = np.ma.array(a, mask=np.ones_like(a))
>>> print np.ma.extras.flatnotmasked_edges(ma)
None
flatnotmasked_edges(a)
Find the indices of the first and last unmasked values.
Expects a 1-D MaskedArray, returns None if all values are masked.
Parameters
arr : array_like
Input 1-D MaskedArray
Returns
edges : ndarray or None
The indices of first and last non-masked value in the array. Returns None if all values
are masked.
See Also:
flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges
Notes
Only accepts 1-D arrays.
Examples
>>> a = np.arange(10)
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> flatnotmasked_edges(ma)
array([3, 8])
notmasked_contiguous(a, axis=None)
Find contiguous unmasked data in a masked array along the given axis.
Parameters
a : array_like
The input array.
axis : int, optional
Axis along which to perform the operation. If None (default), applies to a flattened
version of the array.
Returns
endpoints : list
A list of slices (start and end indexes) of unmasked indexes in the array.
See Also:
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
Notes
Only accepts 2-D arrays at most.
Examples
>>> np.ma.extras.notmasked_contiguous(ma)
[slice(0, 3, None), slice(6, 6, None)]
notmasked_edges(a, axis=None)
Find the indices of the first and last unmasked values along an axis.
If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the
first and last unmasked values respectively.
Parameters
a : array_like
The input array.
axis : int, optional
Axis along which to perform the operation. If None (default), applies to a flattened
version of the array.
Returns
edges : ndarray or list
An array of start and end indexes if there are any masked data in the array. If there are
no masked data in the array, edges is a list of the first and last index.
See Also:
flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous
Examples
>>> np.ma.extras.notmasked_edges(ma)
array([0, 6])
Modifying a mask
ma.mask_cols(a[, axis]) Mask columns of a 2D array that contain masked values.
ma.mask_or(m1, m2[, copy, shrink]) Combine two masks with the logical_or operator.
ma.mask_rowcols(a[, axis]) Mask rows and/or columns of a 2D array that contain masked values.
ma.mask_rows(a[, axis]) Mask rows of a 2D array that contain masked values.
ma.harden_mask(self) Force the mask to hard.
ma.soften_mask(self) Force the mask to soft.
ma.MaskedArray.harden_mask() Force the mask to hard.
ma.MaskedArray.soften_mask() Force the mask to soft.
ma.MaskedArray.shrink_mask() Reduce a mask to nomask when possible.
ma.MaskedArray.unshare_mask() Copy the mask and set the sharedmask flag to False.
mask_cols(a, axis=None)
Mask columns of a 2D array that contain masked values.
This function is a shortcut to mask_rowcols with axis equal to 1.
See Also:
mask_rowcols
Mask rows and/or columns of a 2D array.
masked_where
Mask where a condition is met.
Examples
Examples
mask_rowcols(a, axis=None)
Mask rows and/or columns of a 2D array that contain masked values.
Mask whole rows and/or columns of a 2D array that contain masked values. The masking behavior is selected
using the axis parameter.
If axis is None, rows and columns are masked.
If axis is 0, only rows are masked.
If axis is 1 or -1, only columns are masked.
Parameters
a : array_like, MaskedArray
The array to mask. If not a MaskedArray instance (or if no array elements are masked).
The result is a MaskedArray with mask set to nomask (False). Must be a 2D array.
axis : int, optional
Axis along which to perform the operation. If None, applies to a flattened version of the
array.
Returns
a : MaskedArray
A modified version of the input array, masked depending on the value of the axis pa-
rameter.
Raises
NotImplementedError :
See Also:
mask_rows
Mask rows of a 2D array that contain masked values.
mask_cols
Mask cols of a 2D array that contain masked values.
masked_where
Mask where a condition is met.
Notes
The input arrays mask is modified by this function.
Examples
mask_rows(a, axis=None)
Mask rows of a 2D array that contain masked values.
This function is a shortcut to mask_rowcols with axis equal to 0.
See Also:
mask_rowcols
Mask rows and/or columns of a 2D array.
masked_where
Mask where a condition is met.
Examples
harden_mask
Force the mask to hard.
Whether the mask of a masked array is hard or soft is determined by its hardmask property. harden_mask sets
hardmask to True.
See Also:
hardmask
soften_mask
Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by its hardmask property. soften_mask sets
hardmask to False.
See Also:
hardmask
harden_mask()
Force the mask to hard.
Whether the mask of a masked array is hard or soft is determined by its hardmask property. harden_mask sets
hardmask to True.
See Also:
hardmask
soften_mask()
Force the mask to soft.
Whether the mask of a masked array is hard or soft is determined by its hardmask property. soften_mask sets
hardmask to False.
See Also:
hardmask
shrink_mask()
Reduce a mask to nomask when possible.
Parameters
None :
Returns
None :
Examples
unshare_mask()
Copy the mask and set the sharedmask flag to False.
Whether the mask is shared between masked arrays can be seen from the sharedmask property. unshare_mask
ensures the mask is not shared. A copy of the mask is only made if it was shared.
See Also:
sharedmask
Conversion operations
asanyarray
Similar to asarray, but conserves subclasses.
Examples
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asarray(x))
<class numpy.ma.core.MaskedArray>
asanyarray(a, dtype=None)
Convert the input to a masked array, conserving subclasses.
If a is a subclass of MaskedArray, its class is conserved. No copy is performed if the input is already an ndarray.
Parameters
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {C, F}, optional
Whether to use row-major (C) or column-major (FORTRAN) memory representa-
tion. Default is C.
Returns
out : MaskedArray
MaskedArray interpretation of a.
See Also:
asarray
Similar to asanyarray, but does not conserve subclass.
Examples
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asanyarray(x))
<class numpy.ma.core.MaskedArray>
Notes
A copy is performed by default.
Examples
masked_where
Mask where a condition is met.
masked_values
Mask using floating point equality.
Examples
masked_array(data = [0 1 -- 3],
mask = [False False True False],
fill_value=999999)
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Notes
The array x is prefilled with its filling value.
Examples
masked_invalid(a, copy=True)
Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to masked_where, with condition = ~(np.isfinite(a)). Any pre-existing mask is
conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but
accepts any array_like object.
See Also:
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
Parameters
x : array_like
Array to mask
value : object
Comparison value
copy : {True, False}, optional
Whether to return a copy of x.
shrink : {True, False}, optional
Whether to collapse a mask full of False to nomask
Returns
result : MaskedArray
The result of masking x where equal to value.
See Also:
masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
masked_values
Mask using floating point equality.
Examples
>>> eat
masked_array(data = [cheese ham pineapple],
mask = False,
fill_value=?)
masked_where
Mask where a condition is met.
Notes
The array x is prefilled with its filling value.
Examples
See Also:
masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
Examples
For integers, the fill value will be different in general to the result of masked_equal.
>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> ma.masked_values(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=2)
>>> ma.masked_equal(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=999999)
masked_where(condition, a, copy=True)
Mask an array where a condition is met.
Return a as an array masked where condition is True. Any masked values of a or condition are also masked in
the output.
Parameters
condition : array_like
Masking condition. When condition tests floating point values for equality, consider
using masked_values instead.
a : array_like
Array to mask.
copy : bool
If True (default) make a copy of a in the result. If False modify a in place and return a
view.
Returns
result : MaskedArray
The result of masking a where condition is True.
See Also:
masked_values
Mask using floating point equality.
masked_equal
Mask where equal to a given value.
masked_not_equal
Mask where not equal to a given value.
masked_less_equal
Mask where less than or equal to a given value.
masked_greater_equal
Mask where greater than or equal to a given value.
masked_less
Mask where less than a given value.
masked_greater
Mask where greater than a given value.
masked_inside
Mask inside a given interval.
masked_outside
Mask outside a given interval.
masked_invalid
Mask invalid values (NaNs or infs).
Examples
>>> b = [a, b, c, d]
>>> ma.masked_where(a == 2, b)
masked_array(data = [a b -- d],
mask = [False False True False],
fill_value=N/A)
>>> a = np.arange(4)
>>> a = ma.masked_where(a == 2, a)
>>> a
masked_array(data = [0 1 -- 3],
mask = [False False True False],
fill_value=999999)
>>> b = np.arange(4)
>>> b = ma.masked_where(b == 0, b)
>>> b
masked_array(data = [-- 1 2 3],
mask = [ True False False False],
fill_value=999999)
>>> ma.masked_where(a == 3, b)
masked_array(data = [-- 1 -- --],
mask = [ True False True True],
fill_value=999999)
> to a ndarray
ma.compress_cols(a) Suppress whole columns of a 2-D array that contain masked values.
ma.compress_rowcols(x[, axis]) Suppress the rows and/or columns of a 2-D array that contain
ma.compress_rows(a) Suppress whole rows of a 2-D array that contain masked values.
ma.compressed(x) Return all the non-masked data as a 1-D array.
ma.filled(a[, fill_value]) Return input as an array with masked data replaced by a fill value.
ma.MaskedArray.compressed() Return all the non-masked data as a 1-D array.
ma.MaskedArray.filled([fill_value]) Return a copy of self, with masked values filled with a given value.
compress_cols(a)
Suppress whole columns of a 2-D array that contain masked values.
This is equivalent to np.ma.extras.compress_rowcols(a, 1), see extras.compress_rowcols for de-
tails.
See Also:
extras.compress_rowcols
compress_rowcols(x, axis=None)
Suppress the rows and/or columns of a 2-D array that contain masked values.
The suppression behavior is selected with the axis parameter.
If axis is None, both rows and columns are suppressed.
If axis is 0, only rows are suppressed.
If axis is 1 or -1, only columns are suppressed.
Parameters
axis : int, optional
Axis along which to perform the operation. Default is None.
Returns
compressed_array : ndarray
The compressed array.
Examples
>>> np.ma.extras.compress_rowcols(x)
array([[7, 8]])
>>> np.ma.extras.compress_rowcols(x, 0)
array([[6, 7, 8]])
>>> np.ma.extras.compress_rowcols(x, 1)
array([[1, 2],
[4, 5],
[7, 8]])
compress_rows(a)
Suppress whole rows of a 2-D array that contain masked values.
This is equivalent to np.ma.extras.compress_rowcols(a, 0), see extras.compress_rowcols for de-
tails.
See Also:
extras.compress_rowcols
compressed(x)
Return all the non-masked data as a 1-D array.
This function is equivalent to calling the compressed method of a MaskedArray, see MaskedArray.compressed
for details.
See Also:
MaskedArray.compressed
Equivalent method.
filled(a, fill_value=None)
Return input as an array with masked data replaced by a fill value.
If a is not a MaskedArray, a itself is returned. If a is a MaskedArray and fill_value is None, fill_value is set to
a.fill_value.
Parameters
a : MaskedArray or array_like
An input object.
fill_value : scalar, optional
Filling value. Default is None.
Returns
a : ndarray
The filled array.
See Also:
compressed
Examples
compressed()
Return all the non-masked data as a 1-D array.
Returns
data : ndarray
A new ndarray holding the non-masked data is returned.
Notes
The result is not a MaskedArray!
Examples
filled(fill_value=None)
Return a copy of self, with masked values filled with a given value.
Parameters
fill_value : scalar, optional
The value to use for invalid entries (None by default). If None, the fill_value attribute
of the array is used instead.
Notes
The result is not a MaskedArray!
Examples
Subclassing is preserved. This means that if the data part of the masked array is a matrix, filled returns a matrix:
Raises
NotImplementedError :
When tofile is called.
tolist(fill_value=None)
Return the data portion of the masked array as a hierarchical Python list.
Data items are converted to the nearest compatible Python type. Masked values are converted to fill_value. If
fill_value is None, the corresponding entries in the output list will be None.
Parameters
fill_value : scalar, optional
The value to use for invalid entries. Default is None.
Returns
result : list
The Python list representation of the masked array.
Examples
torecords()
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
the _data field stores the _data part of the array.
the _mask field stores the _mask part of the array.
Parameters
None :
Returns
record : ndarray
A new flexible-type ndarray with two fields: the first element containing a value, the
second element containing the corresponding mask boolean. The returned record shape
matches self.shape.
Notes
A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value,
...) will be lost.
Examples
tostring(fill_value=None, order=C)
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
Parameters
fill_value : scalar, optional
Value used to fill in the masked values. Deafult is None, in which case MaskedAr-
ray.fill_value is used.
order : {C,F,A}, optional
Notes
As for ndarray.tostring, information about the shape, dtype, etc., but also about fill_value, will be lost.
Examples
dump
Pickle an array
Notes
This is different from numpy.load, which does not use cPickle but loads the NumPy binary .npy format.
loads(strg)
Load a pickle from the current string.
The result of cPickle.loads(strg) is returned.
Parameters
strg : str
The string to load.
See Also:
dumps
Return a string corresponding to the pickling of a masked array.
Examples
default_fill_value(obj)
Return the default fill value for the argument object.
The default filling value depends on the datatype of the input array or the type of the input scalar:
datatype default
bool True
int 999999
float 1.e20
complex 1.e20+0j
object ?
string N/A
Parameters
obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value is returned.
Returns
fill_value : scalar
The default fill value.
Examples
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)
maximum_fill_value(obj)
Return the minimum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype.
Parameters
obj : {ndarray, dtype}
An object that can be queried for its numeric type.
Returns
val : scalar
The minimum representable value.
Raises
TypeError :
If obj isnt a suitable numeric type.
See Also:
minimum_fill_value
The inverse function.
set_fill_value
Set the filling value of a masked array.
MaskedArray.fill_value
Return current fill value.
Examples
maximum_fill_value(obj)
Return the minimum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype.
Parameters
obj : {ndarray, dtype}
An object that can be queried for its numeric type.
Returns
val : scalar
The minimum representable value.
Raises
TypeError :
If obj isnt a suitable numeric type.
See Also:
minimum_fill_value
The inverse function.
set_fill_value
Set the filling value of a masked array.
MaskedArray.fill_value
Return current fill value.
Examples
set_fill_value(a, fill_value)
Set the filling value of a, if a is a masked array.
This function changes the fill value of the masked array a in place. If a is not a masked array, the function
returns silently, without doing anything.
Parameters
a : array_like
Input array.
fill_value : dtype
Filling value. A consistency test is performed to make sure the value is compatible with
the dtype of a.
Returns
None :
Nothing returned by this function.
See Also:
maximum_fill_value
Return the default fill value for a dtype.
MaskedArray.fill_value
Return current fill value.
MaskedArray.set_fill_value
Equivalent method.
Examples
>>> a = range(5)
>>> a
[0, 1, 2, 3, 4]
>>> ma.set_fill_value(a, 100)
>>> a
[0, 1, 2, 3, 4]
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> ma.set_fill_value(a, 100)
>>> a
array([0, 1, 2, 3, 4])
get_fill_value()
Return the filling value of the masked array.
Returns
fill_value : scalar
The filling value.
Examples
set_fill_value(value=None)
Set the filling value of the masked array.
Parameters
value : scalar, optional
The new filling value. Default is None, in which case a default based on the data type
is used.
See Also:
ma.set_fill_value
Equivalent function.
Examples
Reset to default:
>>> x.set_fill_value()
>>> x.fill_value
1e+20
fill_value
Filling value.
Arithmetics
ma.anom(self[, axis, dtype]) Compute the anomalies (deviations from the arithmetic mean) along
the given axis.
ma.anomalies(self[, axis, dtype]) Compute the anomalies (deviations from the arithmetic mean) along
the given axis.
ma.average(a[, axis, weights, Return the weighted average of array over the given axis.
returned])
ma.conjugate() Return the complex conjugate, element-wise.
ma.corrcoef(x[, y, rowvar, bias, Return correlation coefficients of the input array.
allow_masked])
ma.cov(x[, y, rowvar, bias, Estimate the covariance matrix.
allow_masked])
ma.cumsum(self[, axis, dtype, out]) Return the cumulative sum of the elements along the given axis.
ma.cumprod(self[, axis, dtype, out]) Return the cumulative product of the elements along the given axis.
ma.mean(self[, axis, dtype, out]) Returns the average of the array elements.
ma.median(a[, axis, out, Compute the median along the specified axis.
overwrite_input])
ma.power(a, b[, third]) Returns element-wise base array raised to power from second array.
ma.prod(self[, axis, dtype, out]) Return the product of the array elements over the given axis.
ma.std(self[, axis, dtype, out, ddof]) Compute the standard deviation along the specified axis.
ma.sum(self[, axis, dtype, out]) Return the sum of the array elements over the given axis.
ma.var(self[, axis, dtype, out, ddof]) Compute the variance along the specified axis.
ma.MaskedArray.anom([axis, dtype]) Compute the anomalies (deviations from the arithmetic mean) along
the given axis.
ma.MaskedArray.cumprod([axis, Return the cumulative product of the elements along the given axis.
dtype, out])
ma.MaskedArray.cumsum([axis, Return the cumulative sum of the elements along the given axis.
dtype, out])
ma.MaskedArray.mean([axis, dtype, Returns the average of the array elements.
out])
ma.MaskedArray.prod([axis, dtype, Return the product of the array elements over the given axis.
out])
ma.MaskedArray.std([axis, dtype, Compute the standard deviation along the specified axis.
out, ddof])
ma.MaskedArray.sum([axis, dtype, Return the sum of the array elements over the given axis.
out])
ma.MaskedArray.var([axis, dtype, Compute the variance along the specified axis.
out, ddof])
anom
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
anomalies
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
Parameters
a : array_like
Data to be averaged. Masked entries are not taken into account in the computation.
axis : int, optional
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
weights : array_like, optional
The importance that each element has in the computation of the average. The weights
array can either be 1-D (in which case its length must be the size of a along the given
axis) or of the same shape as a. If weights=None, then all data in a are assumed to
have a weight equal to one.
returned : bool, optional
Flag indicating whether a tuple (result, sum of weights) should be returned
as output (True), or just the result (False). Default is False.
Returns
average, [sum_of_weights] : (tuple of) scalar or MaskedArray
The average along the specified axis. When returned is True, return a tuple with the
average as the first element and the sum of the weights as the second element. The
return type is np.float64 if a is of integer type, otherwise it is of the same type as a. If
returned, sum_of_weights is of the same type as average.
Examples
>>> x = np.ma.arange(6.).reshape(3, 2)
>>> print x
[[ 0. 1.]
[ 2. 3.]
[ 4. 5.]]
>>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
... returned=True)
>>> print avg
[2.66666666667 3.66666666667]
conjugate
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.
Parameters
x : array_like
Input value.
Returns
y : ndarray
The complex conjugate of x, with same dtype as y.
Examples
>>> np.conjugate(1+2j)
(1-2j)
numpy.corrcoef
Equivalent function in top-level NumPy module.
cov
Estimate the covariance matrix.
Parameters
x : array_like
A 1-D or 2-D array containing multiple variables and observations. Each row of x
represents a variable, and each column a single observation of all those variables. Also
see rowvar below.
y : array_like, optional
An additional set of variables and observations. y has the same form as x.
rowvar : bool, optional
If rowvar is True (default), then each row represents a variable, with observations in the
columns. Otherwise, the relationship is transposed: each column represents a variable,
while the rows contain observations.
bias : bool, optional
Default normalization (False) is by (N-1), where N is the number of observations given
(unbiased estimate). If bias is True, then normalization is by N.
allow_masked : bool, optional
If True, masked values are propagated pair-wise: if a value is masked in x, the cor-
responding value is masked in y. If False, raises a ValueError exception when some
values are missing.
Raises
ValueError: :
Raised if some values are missing and allow_masked is False.
See Also:
numpy.cov
cumsum
Return the cumulative sum of the elements along the given axis. The cumulative sum is calculated over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array. axis may be negative, in which case it counts from the last to the
first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the elements are summed. If
dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a
precision less than that of the default platform integer. In that case, the default platform
integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumsum : ndarray.
A new array holding the result is returned unless out is specified, in which case a
reference to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
cumprod
Return the cumulative product of the elements along the given axis. The cumulative product is taken over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 1 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the product is computed. The default (axis = None) is to compute
over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements
are multiplied. If dtype has the value None and the type of a is an integer type
of precision less than the default platform integer, then the default platform integer
precision is used. Otherwise, the dtype is the same as that of a.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumprod : ndarray
A new array holding the result is returned unless out is specified, in which case a refer-
ence to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
mean
Returns the average of the array elements.
Masked entries are ignored. The average is taken over the flattened array by default, otherwise over the specified
axis. Refer to numpy.mean for the full documentation.
Parameters
a : array_like
Array containing numbers whose mean is desired. If a is not an array, a conversion is
attempted.
numpy.ma.mean
Equivalent function.
numpy.mean
Equivalent function on non-masked arrays.
numpy.ma.average
Weighted average.
Examples
If True, then allow use of memory of input array (a) for calculations. The input array
will be modified by the call to median. This will save memory when you do not need to
preserve the contents of the input array. Treat the input as undefined, but it will probably
be fully or partially sorted. Default is False. Note that, if overwrite_input is True, and
the input is not already an ndarray, an error will be raised.
Returns
median : ndarray
A new array holding the result is returned unless out is specified, in which case a refer-
ence to out is returned. Return data-type is float64 for integers and floats smaller than
float64, or the input data-type, otherwise.
See Also:
mean
Notes
Given a vector V with N non masked values, the median of V is the middle value of a sorted copy of V (Vs) - i.e.
Vs[(N-1)/2], when N is odd, or {Vs[N/2 - 1] + Vs[N/2]}/2 when N is even.
Examples
power(a, b, third=None)
Returns element-wise base array raised to power from second array.
This is the masked array version of numpy.power. For details see numpy.power.
See Also:
numpy.power
Notes
The out argument to numpy.power is not supported, third has to be None.
prod
Return the product of the array elements over the given axis. Masked elements are set to 1 internally for
computation.
Parameters
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the product is over all the
array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements are
multiplied. If dtype has the value None and the type of a is an integer type of precision
less than the default platform integer, then the default platform integer precision is used.
Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type will be cast if necessary.
Returns
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified axis removed. Returns
a 0d array when a is 1d or axis=None. Returns a reference to the specified output array
if specified.
See Also:
prod
equivalent function
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
std
Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard
deviation is computed for the flattened array by default, otherwise over the specified axis.
Parameters
a : array_like
Calculate the standard deviation of these values.
axis : int, optional
Axis along which the standard deviation is computed. The default is to compute the
standard deviation of the flattened array.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of integer type the default
is float64, for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type (of the calculated values) will be cast if necessary.
Notes
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =
sqrt(mean(abs(x - x.mean())**2)).
The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however,
ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate
of the variance for normally distributed variables. The standard deviation computed in this function is the
square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard
deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real
and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input
data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-
accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
sum
Return the sum of the array elements over the given axis. Masked elements are set to 0 internally.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements
are summed. If dtype has the value None and the type of a is an integer type of precision
less than the default platform integer, then the default platform integer precision is used.
Otherwise, the dtype is the same as that of a.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
sum_along_axis : MaskedArray or scalar
An array with the same shape as self, with the specified axis removed. If self is a 0-d
array, or if axis is None, a scalar is returned. If an output array is specified, a reference
to out is returned.
Examples
var
Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed
for the flattened array by default, otherwise over the specified axis.
Parameters
a : array_like
Array containing numbers whose variance is desired. If a is not an array, a conversion
is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type the default is float32;
for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type is cast if necessary.
ddof : int, optional
Delta Degrees of Freedom: the divisor used in calculation is N - ddof, where N
represents the number of elements. By default ddof is zero.
Returns
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise a reference to the
output array is returned.
See Also:
std
Standard deviation
mean
Average
numpy.doc.ufuncs
Section Output arguments
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x -
x.mean())**2).
The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the
divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of
the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for
normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and
nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the
input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a
higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
anom(axis=None, dtype=None)
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
of precision less than the default platform integer, then the default platform integer
precision is used. Otherwise, the dtype is the same as that of a.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumprod : ndarray
A new array holding the result is returned unless out is specified, in which case a refer-
ence to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis. The cumulative sum is calculated over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array. axis may be negative, in which case it counts from the last to the
first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the elements are summed. If
dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a
precision less than that of the default platform integer. In that case, the default platform
integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumsum : ndarray.
A new array holding the result is returned unless out is specified, in which case a
reference to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
numpy.ma.mean
Equivalent function.
numpy.mean
Equivalent function on non-masked arrays.
numpy.ma.average
Weighted average.
Examples
prod
equivalent function
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type (of the calculated values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements. By default ddof is zero.
Returns
standard_deviation : ndarray, see dtype parameter above.
If out is None, return a new array containing the standard deviation, otherwise return a
reference to the output array.
See Also:
var, mean
numpy.doc.ufuncs
Section Output arguments
Notes
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =
sqrt(mean(abs(x - x.mean())**2)).
The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however,
ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate
of the variance for normally distributed variables. The standard deviation computed in this function is the
square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard
deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real
and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input
data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-
accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
Examples
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type the default is float32;
for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type is cast if necessary.
ddof : int, optional
Delta Degrees of Freedom: the divisor used in calculation is N - ddof, where N
represents the number of elements. By default ddof is zero.
Returns
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise a reference to the
output array is returned.
See Also:
std
Standard deviation
mean
Average
numpy.doc.ufuncs
Section Output arguments
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x -
x.mean())**2).
The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the
divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of
the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for
normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and
nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the
input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a
higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
Minimum/maximum
ma.argmax(a[, axis, fill_value]) Function version of the eponymous method.
ma.argmin(a[, axis, fill_value]) Returns array of indices of the maximum values along the
given axis.
ma.max(obj[, axis, out, fill_value]) Return the maximum along a given axis.
ma.min(obj[, axis, out, fill_value]) Return the minimum along a given axis.
ma.ptp(obj[, axis, out, fill_value]) Return (maximum - minimum) along the the given dimension
(i.e.
ma.MaskedArray.argmax([axis, fill_value, Returns array of indices of the maximum values along the
out]) given axis.
ma.MaskedArray.argmin([axis, fill_value, Return array of indices to the minimum values along the given
out]) axis.
ma.MaskedArray.max([axis, out, Return the maximum along a given axis.
fill_value])
ma.MaskedArray.min([axis, out, Return the minimum along a given axis.
fill_value])
ma.MaskedArray.ptp([axis, out, Return (maximum - minimum) along the the given dimension
fill_value]) (i.e.
argmax(a, axis=None, fill_value=None)
Function version of the eponymous method.
argmin(a, axis=None, fill_value=None)
Returns array of indices of the maximum values along the given axis. Masked values are treated as if they had
the value fill_value.
Parameters
axis : {None, integer}
If None, the index is into the flattened array, otherwise along the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of maxi-
mum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
Returns
index_array : {integer_array}
Examples
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
maximum_fill_value
Returns the maximum filling value for a given datatype.
minimum_fill_value
Returns the minimum filling value for a given datatype.
Examples
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
If None, the index is into the flattened array, otherwise along the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of mini-
mum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
Returns
{ndarray, scalar} :
If multi-dimension input, returns a new ndarray of indices to the minimum values along
the given axis. Otherwise, returns a scalar of index to the minimum values along the
given axis.
Examples
maximum_fill_value
Returns the maximum filling value for a given datatype.
Parameters
axis : {None, int}, optional
Axis along which to operate. By default, axis is None and the flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of the same shape and
buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values. If None, use the output of minimum_fill_value.
Returns
amin : array_like
New array holding the result. If out was specified, out is returned.
See Also:
minimum_fill_value
Returns the minimum filling value for a given datatype.
Sorting
ma.argsort(a[, axis, kind, order, fill_value]) Return an ndarray of indices that sort the array along the
specified axis.
ma.sort(a[, axis, kind, order, endwith, ...]) Sort the array, in-place
ma.MaskedArray.argsort([axis, kind, Return an ndarray of indices that sort the array along the
order, ...]) specified axis.
ma.MaskedArray.sort([axis, kind, order, Sort the array, in-place
...])
argsort(a, axis=None, kind=quicksort, order=None, fill_value=None)
Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to
fill_value.
Parameters
axis : int, optional
Axis along which to sort. The default is -1 (last axis). If None, the flattened array is
used.
fill_value : var, optional
Value used to fill the array before sorting. The default is the fill_value attribute of the
input array.
kind : {quicksort, mergesort, heapsort}, optional
Sorting algorithm.
order : list, optional
When a is an array with fields defined, this argument specifies which fields to compare
first, second, etc. Not all fields need be specified.
Returns
index_array : ndarray, int
Array of indices that sort a along the specified axis. In other words,
a[index_array] yields a sorted a.
See Also:
sort
Describes sorting algorithms used.
lexsort
Indirect stable sort with multiple keys.
ndarray.sort
Inplace sort.
Notes
See sort for notes on the different sorting algorithms.
Examples
ndarray.sort
Method to sort an array in-place.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in a sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
sort
Describes sorting algorithms used.
lexsort
Indirect stable sort with multiple keys.
ndarray.sort
Inplace sort.
Notes
See sort for notes on the different sorting algorithms.
Examples
ndarray.sort
Method to sort an array in-place.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in a sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Algebra
ma.diag(v[, k]) Extract a diagonal or construct a diagonal array.
ma.dot(a, b[, strict]) Return the dot product of two arrays.
ma.identity(n[, dtype]) Return the identity array.
ma.inner(a, b) Inner product of two arrays.
ma.innerproduct(a, b) Inner product of two arrays.
ma.outer(a, b) Compute the outer product of two vectors.
ma.outerproduct(a, b) Compute the outer product of two vectors.
ma.trace(self[, offset, axis1, axis2, ...]) Return the sum along diagonals of the array.
ma.transpose(a[, axes]) Permute the dimensions of an array.
ma.MaskedArray.trace([offset, axis1, axis2, ...]) Return the sum along diagonals of the array.
ma.MaskedArray.transpose(*axes) Returns a view of the array with axes transposed.
diag(v, k=0)
Extract a diagonal or construct a diagonal array.
This function is the equivalent of numpy.diag that takes masked values into account, see numpy.diag for
details.
See Also:
numpy.diag
Equivalent function for ndarrays.
dot(a, b, strict=False)
Return the dot product of two arrays.
Note: Works only with 2-D arrays at the moment.
This function is the equivalent of numpy.dot that takes masked values into account, see numpy.dot for
details.
Parameters
a, b : ndarray
Inputs arrays.
strict : bool, optional
Whether masked data are propagated (True) or set to 0 (False) for the computation.
Default is False. Propagating the mask means that if a masked value appears in a row
or column, the whole row or column is considered masked.
See Also:
numpy.dot
Equivalent function for ndarrays.
Examples
identity
Return the identity array.
The identity array is a square array with ones on the main diagonal.
Parameters
n : int
Number of rows (and columns) in n x n output.
dtype : data-type, optional
Data-type of the output. Defaults to float.
Returns
out : ndarray
n x n array with its main diagonal set to one, and all other elements 0.
Examples
>>> np.identity(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
inner(a, b)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum
product over the last axes.
Parameters
a, b : array_like
If a and b are nonscalar, their last dimensions of must match.
Returns
out : ndarray
out.shape = a.shape[:-1] + b.shape[:-1]
Raises
ValueError :
If the last dimension of a and b has different size.
See Also:
tensordot
Sum products over arbitrary axes.
dot
Generalised matrix product, using second last dimension of b.
Notes
Masked values are replaced by 0.
Examples
Ordinary inner product for vectors:
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
A multidimensional example:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])
innerproduct(a, b)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum
product over the last axes.
Parameters
a, b : array_like
If a and b are nonscalar, their last dimensions of must match.
Returns
out : ndarray
out.shape = a.shape[:-1] + b.shape[:-1]
Raises
ValueError :
If the last dimension of a and b has different size.
See Also:
tensordot
Sum products over arbitrary axes.
dot
Generalised matrix product, using second last dimension of b.
Notes
Masked values are replaced by 0.
Examples
Ordinary inner product for vectors:
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
A multidimensional example:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])
outer(a, b)
Compute the outer product of two vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [R57]
is:
Parameters
a, b : array_like, shape (M,), (N,)
First and second input vectors. Inputs are flattened if they are not already 1-dimensional.
Returns
out : ndarray, shape (M, N)
out[i, j] = a[i] * b[j]
Notes
Masked values are replaced by 0.
References
[R57]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:
outerproduct(a, b)
Compute the outer product of two vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [R58]
is:
Parameters
a, b : array_like, shape (M,), (N,)
First and second input vectors. Inputs are flattened if they are not already 1-dimensional.
Returns
out : ndarray, shape (M, N)
out[i, j] = a[i] * b[j]
Notes
Masked values are replaced by 0.
References
[R58]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:
trace
numpy.trace
equivalent function
transpose(a, axes=None)
Permute the dimensions of an array.
This function is exactly equivalent to numpy.transpose.
See Also:
numpy.transpose
Equivalent function in top-level NumPy module.
Examples
numpy.trace
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a ma-
trix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order in-
dicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1],
... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1],
i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s j-th
axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
Polynomial fit
ma.vander(x[, n]) Generate a Van der Monde matrix.
ma.polyfit(x, y, deg[, rcond, full]) Least squares polynomial fit.
vander(x, n=None)
Generate a Van der Monde matrix.
The columns of the output matrix are decreasing powers of the input vector. Specifically, the i-th output column
is the input vector to the power of N - i - 1. Such a matrix with a geometric progression in each row is
named Van Der Monde, or Vandermonde matrix, from Alexandre-Theophile Vandermonde.
Parameters
x : array_like
1-D input array.
N : int, optional
Order of (number of columns in) the output. If N is not specified, a square array is
returned (N = len(x)).
Returns
out : ndarray
Van der Monde matrix of order N. The first column is x^(N-1), the second x^(N-2)
and so forth.
Notes
Masked values in the input array result in rows of zeros.
References
[R61]
Examples
The determinant of a square Vandermonde matrix is the product of the differences between the values of the
input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
Switch determining nature of return value. When it is False (the default) just the coef-
ficients are returned, when True diagnostic information from the singular value decom-
position is also returned.
Returns
p : ndarray, shape (M,) or (M, K)
Polynomial coefficients, highest power first. If y was 2-D, the coefficients for k-th data
set are in p[:,k].
residuals, rank, singular_values, rcond : present only if full = True
Residuals of the least-squares fit, the effective rank of the scaled Vandermonde coeffi-
cient matrix, its singular values, and the specified value of rcond. For more details, see
linalg.lstsq.
See Also:
polyval
Computes polynomial values.
linalg.lstsq
Computes a least-squares fit.
scipy.interpolate.UnivariateSpline
Computes spline fits.
Notes
Any masked values in x is propagated in y, and vice-versa.
References
[R59], [R60]
Examples
>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179
>>> p(3.5)
-0.34732142857143039
>>> p(10)
22.579365079365115
-0.99999999999999445
>>> p30(4.5)
-0.10547061179440398
Illustration:
2.0
1.5
1.0
0.5
0.0
0.5
1.0
1.5
2.0
2 1 0 1 2 3 4 5 6
around
equivalent function
Parameters
a : array_like
Array containing elements to clip.
a_min : scalar or array_like
Minimum value.
a_max : scalar or array_like
Maximum value. If a_min or a_max are array_like, then they will be broadcasted to the
shape of a.
out : ndarray, optional
The results will be placed in this array. It may be the input array for in-place clipping.
out must be of the right shape to hold the output. Its type is preserved.
Returns
clipped_array : ndarray
An array with the elements of a, but where values < a_min are replaced with a_min, and
those > a_max with a_max.
See Also:
numpy.doc.ufuncs
Section Output arguments
Examples
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
Notes
If out is given and does not have a mask attribute, the mask of a is lost!
clip(a_min, a_max, out=None)
Return an array whose values are limited to [a_min, a_max].
Refer to numpy.clip for full documentation.
See Also:
numpy.clip
equivalent function
round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to numpy.around for full documentation.
See Also:
numpy.around
equivalent function
Miscellanea
ma.allequal(a, b[, fill_value]) Return True if all entries of a and b are equal, using
ma.allclose(a, b[, masked_equal, rtol, Returns True if two arrays are element-wise equal within a
...]) tolerance.
ma.apply_along_axis(func1d, axis, Apply a function to 1-D slices along the given axis.
arr, ...)
ma.arange([dtype]) Return evenly spaced values within a given interval.
ma.choose(indices, choices[, out, mode]) Use an index array to construct a new array from a set of choices.
ma.ediff1d(arr[, to_end, to_begin]) Compute the differences between consecutive elements of an array.
ma.indices(dimensions[, dtype]) Return an array representing the indices of a grid.
ma.where(condition[, x, y]) Return a masked array with elements from x or y, depending on
condition.
allequal(a, b, fill_value=True)
Return True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked.
Parameters
a, b : array_like
Input arrays to compare.
fill_value : bool, optional
Whether masked values in a or b are considered equal (True) or not (False).
Returns
y : bool
Returns True if the two arrays are equal within the given tolerance, False otherwise. If
either array contains NaN, then False is returned.
See Also:
all, any, numpy.ma.allclose
Examples
Notes
If the following equation is element-wise True, then allclose returns True:
Return True if all elements of a and b are equal subject to given tolerances.
Examples
See Also:
apply_over_axes
Apply a function repeatedly over multiple axes.
Examples
For a function that doesnt return a scalar, the number of dimensions in outarr is the same as arr.
arange
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including
start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function,
but returns a ndarray rather than a list.
Parameters
start : number, optional
Start of interval. The interval includes this value. The default start value is 0.
stop : number
End of interval. The interval does not include this value.
step : number, optional
Spacing between values. For any output out, this is the distance between two adjacent
values, out[i+1] - out[i]. The default step size is 1. If step is specified, start
must also be given.
dtype : dtype
The type of the output array. If dtype is not given, infer the data type from the other
input arguments.
Returns
out : ndarray
Array of evenly spaced values.
linspace
Evenly spaced numbers with careful handling of endpoints.
ogrid
Arrays of evenly spaced numbers in N-dimensions
mgrid
Grid-shaped arrays of evenly spaced numbers in N-dimensions
Examples
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
choose
equivalent function
Examples
numpy.ediff1d
Equivalent function for ndarrays.
Notes
The output shape is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if
dimensions is a tuple (r0, ..., rN-1) of length N, the output shape is (N,r0,...,rN-1).
The subarrays grid[k] contains the N-D array of indices along the k-th axis. Explicitly:
grid[k,i0,i1,...,iN-1] = ik
Examples
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
[4, 5, 6]])
Note that it would be more straightforward in the above example to extract the required elements directly with
x[:2, :3].
where(condition, x=None, y=None)
Return a masked array with elements from x or y, depending on condition.
Returns a masked array, shaped like condition, where the elements are from x when condition is True, and from
y otherwise. If neither x nor y are given, the function returns a tuple of indices where condition is True (the
result of condition.nonzero()).
Parameters
condition : array_like, bool
The condition to meet. For each True element, yield the corresponding element from x,
otherwise from y.
x, y : array_like, optional
Values from which to choose. x and y need to have the same shape as condition, or be
broadcast-able to that shape.
Returns
out : MaskedArray or tuple of ndarrays
The resulting masked array if x and y were given, otherwise the result of
condition.nonzero().
See Also:
numpy.where
Equivalent function in the top-level NumPy module.
Examples
Warning: This page describes the old, deprecated array interface. Everything still works as described as of numpy
1.2 and on into the foreseeable future, but new development should target PEP 3118 The Revised Buffer
Protocol. PEP 3118 was incorporated into Python 2.6 and 3.0, and is additionally supported by Cythons
numpy buffer support. (See the Cython numpy tutorial.) Cython provides a way to write code that supports the
buffer protocol with Python versions older than 2.6 because it has a backward-compatible implementation utilizing
the legacy array interface described here.
version
3
The array interface (sometimes called array protocol) was created in 2005 as a means for array-like Python objects to
re-use each others data buffers intelligently whenever possible. The homogeneous N-dimensional array interface is
a default mechanism for objects to share N-dimensional array memory and information. The interface consists of a
Python-side and a C-side using two attributes. Objects wishing to be considered an N-dimensional array in application
code should support at least one of these attributes. Objects wishing to support an N-dimensional array in application
code should look for at least one of these attributes and use the information provided appropriately.
This interface describes homogeneous arrays in the sense that each item of the array has the same type. This type
can be very simple or it can be a quite arbitrary and complicated C-like structure.
There are two ways to use the interface: A Python side and a C-side. Both are separate attributes.
This approach to the interface consists of the object having an __array_interface__ attribute.
__array_interface__
A dictionary of items (3 required and 5 optional). The optional keys in the dictionary have implied defaults if
they are not provided.
The keys are:
shape (required)
Tuple whose elements are the array size in each dimension. Each entry is an integer (a Python int or
long). Note that these integers could be larger than the platform int or long could hold (a Python
int is a C long). It is up to the code using this attribute to handle this appropriately; either by raising
an error when overflow is possible, or by using Py_LONG_LONG as the C type for the shapes.
typestr (required)
A string providing the basic type of the homogenous array The basic string format consists of 3 parts:
a character describing the byteorder of the data (<: little-endian, >: big-endian, |: not-relevant), a
character code giving the basic type of the array, and an integer providing the number of bytes the
type uses.
The basic type character codes are:
t Bit field (following integer gives the number of bits in the bit field).
b Boolean (integer type where all values are only True or False)
i Integer
u Unsigned integer
f Floating point
c Complex floating point
O Object (i.e. the memory contains a pointer to PyObject)
S String (fixed-length sequence of char)
U Unicode (fixed-length sequence of Py_UNICODE)
V Other (void * each item is a fixed-size chunk of memory)
descr (optional)
A list of tuples providing a more detailed description of the memory layout for each item in the
homogeneous array. Each tuple in the list has two or three elements. Normally, this attribute would
be used when typestr is V[0-9]+, but this is not a requirement. The only requirement is that the
number of bytes represented in the typestr key is the same as the total number of bytes represented
here. The idea is to support descriptions of C-like structs (records) that make up array elements. The
elements of each tuple in the list are
1.A string providing a name associated with this portion of the record. This could also be a tuple
of (full name, basic_name) where basic name would be a valid Python variable
name representing the full name of the field.
2.Either a basic-type description string as in typestr or another list (for nested records)
3.An optional shape tuple providing how many times this part of the record should be repeated. No
repeats are assumed if this is not given. Very complicated structures can be described using this
generic interface. Notice, however, that each element of the array is still of the same data-type.
Some examples of using this interface are given below.
Default: [(, typestr)]
data (optional)
A 2-tuple whose first argument is an integer (a long integer if necessary) that points to the data-area
storing the array contents. This pointer must point to the first element of data (in other words any
offset is always ignored in this case). The second entry in the tuple is a read-only flag (true means
the data area is read-only).
This attribute can also be an object exposing the buffer interface which will be used to share
the data. If this key is not present (or returns None), then memory sharing will be done through the
buffer interface of the object itself. In this case, the offset key can be used to indicate the start of the
buffer. A reference to the object exposing the array interface must be stored by the new object if the
memory area is to be secured.
Default: None
strides (optional)
Either None to indicate a C-style contiguous array or a Tuple of strides which provides the number of
bytes needed to jump to the next array element in the corresponding dimension. Each entry must be
an integer (a Python int or long). As with shape, the values may be larger than can be represented
by a C int or long; the calling code should handle this appropiately, either by raising an error, or
by using Py_LONG_LONG in C. The default is None which implies a C-style contiguous memory
buffer. In this model, the last dimension of the array varies the fastest. For example, the default
strides tuple for an object whose array entries are 8 bytes long and whose shape is (10,20,30) would
be (4800, 240, 8)
Default: None (C-style contiguous)
mask (optional)
None or an object exposing the array interface. All elements of the mask array should be interpreted
only as true or not true indicating which elements of this array are valid. The shape of this object
should be broadcastable to the shape of the original array.
Default: None (All array values are valid)
offset (optional)
An integer offset into the array data region. This can only be used when data is None or returns a
buffer object.
Default: 0.
version (required)
An integer showing the version of the interface (i.e. 3 for this version). Be careful not to use this to
invalidate objects exposing future versions of the interface.
This approach to the array interface allows for faster access to an array using only one attribute lookup and a well-
defined C-structure.
__array_struct__
A PyCObject whose voidptr member contains a pointer to a filled PyArrayInterface structure.
Memory for the structure is dynamically created and the PyCObject is also created with an appropriate
destructor so the retriever of this attribute simply has to apply Py_DECREF to the object returned by this
attribute when it is finished. Also, either the data needs to be copied out, or a reference to the object exposing
this attribute must be held to ensure the data is not freed. Objects exposing the __array_struct__ interface
must also not reallocate their memory if other objects are referencing them.
The PyArrayInterface structure is defined in numpy/ndarrayobject.h as:
typedef struct {
int two; /* contains the integer 2 -- simple sanity check */
int nd; /* number of dimensions */
char typekind; /* kind in array --- character code of typestr */
int itemsize; /* size of each element */
int flags; /* flags indicating how the data should be interpreted */
/* must set ARR_HAS_DESCR bit to validate descr */
Py_intptr_t *shape; /* A length-nd array of shape information */
Py_intptr_t *strides; /* A length-nd array of stride information */
void *data; /* A pointer to the first element of the array */
PyObject *descr; /* NULL or data-description (same as descr key
of __array_interface__) -- must set ARR_HAS_DESCR
flag or this will be ignored. */
} PyArrayInterface;
The flags member may consist of 5 bits showing how the data should be interpreted and one bit showing how
the Interface should be interpreted. The data-bits are CONTIGUOUS (0x1), FORTRAN (0x2), ALIGNED (0x100),
NOTSWAPPED (0x200), and WRITEABLE (0x400). A final flag ARR_HAS_DESCR (0x800) indicates whether or not
this structure has the arrdescr field. The field should not be accessed unless this flag is present.
New since June 16, 2006:
In the past most implementations used the desc member of the PyCObject itself (do not confuse this with the
descr member of the PyArrayInterface structure above they are two separate things) to hold the pointer to
the object exposing the interface. This is now an explicit part of the interface. Be sure to own a reference to the object
when the PyCObject is created using PyCObject_FromVoidPtrAndDesc.
For clarity it is useful to provide some examples of the type description and corresponding __array_interface__
descr entries. Thanks to Scott Gilbert for these examples:
In every case, the descr key is optional, but of course provides more information which may be important for various
applications:
* Float data
typestr == >f4
descr == [(,>f4)]
* Complex double
typestr == >c8
descr == [(real,>f4), (imag,>f4)]
* Nested structure
struct {
int ival;
struct {
unsigned short sval;
unsigned char bval;
unsigned char cval;
} sub;
}
typestr == |V8 (or <u8 if you want)
descr == [(ival,<i4), (sub, [(sval,<u2), (bval,|u1), (cval,|u1) ]) ]
* Nested array
struct {
int ival;
double data[16*4];
}
typestr == |V516
descr == [(ival,>i4), (data,>f8,(16,4))]
* Padded structure
struct {
int ival;
double dval;
}
typestr == |V16
descr == [(ival,>i4),(,|V4),(dval,>f8)]
It should be clear that any record type could be described using this interface.
The version 2 interface was very similar. The differences were largely asthetic. In particular:
1. The PyArrayInterface structure had no descr member at the end (and therefore no flag ARR_HAS_DESCR)
2. The desc member of the PyCObject returned from __array_struct__ was not specified. Usually, it was the object
exposing the array (so that a reference to it could be kept and destroyed when the C-object was destroyed). Now
it must be a tuple whose first element is a string with PyArrayInterface Version # and whose second element
is the object exposing the array.
3. The tuple returned from __array_interface__[data] used to be a hex-string (now it is an integer or a long
integer).
4. There was no __array_interface__ attribute instead all of the keys (except for version) in the __array_interface__
dictionary were their own attribute: Thus to obtain the Python-side information you had to access separately the
attributes:
__array_data__
__array_shape__
__array_strides__
__array_typestr__
__array_descr__
__array_offset__
__array_mask__
TWO
A universal function (or ufunc for short) is a function that operates on ndarrays in an element-by-element fashion,
supporting array broadcasting, type casting, and several other standard features. That is, a ufunc is a vectorized
wrapper for a function that takes a fixed number of scalar inputs and produces a fixed number of scalar outputs.
In Numpy, universal functions are instances of the numpy.ufunc class. Many of the built-in functions are imple-
mented in compiled C code, but ufunc instances can also be produced using the frompyfunc factory function.
2.1 Broadcasting
Each universal function takes array inputs and produces array outputs by performing the core function element-wise
on the inputs. Standard broadcasting rules are applied so that inputs not sharing exactly the same shapes can still be
usefully operated on. Broadcasting can be understood by four rules:
1. All input arrays with ndim smaller than the input array of largest ndim, have 1s prepended to their shapes.
2. The size in each dimension of the output shape is the maximum of all the input sizes in that dimension.
3. An input can be used in the calculation if its size in a particular dimension either matches the output size in that
dimension, or has value exactly 1.
4. If an input has a dimension size of 1 in its shape, the first data entry in that dimension will be used for all
calculations along that dimension. In other words, the stepping machinery of the ufunc will simply not step
along that dimension (the stride will be 0 for that dimension).
Broadcasting is used throughout NumPy to decide how to handle disparately shaped arrays; for example, all arith-
metic operations (+, -, *, ...) between ndarrays broadcast the arrays before operation. A set of arrays is called
broadcastable to the same shape if the above rules produce a valid result, i.e., one of the following is true:
1. The arrays all have exactly the same shape.
2. The arrays all have the same number of dimensions and the length of each dimensions is either a common length
or 1.
3. The arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy
property 2.
Example
If a.shape is (5,1), b.shape is (1,6), c.shape is (6,) and d.shape is () so that d is a scalar, then a, b, c, and d
are all broadcastable to dimension (5,6); and
a acts like a (5,6) array where a[:,0] is broadcast to the other columns,
b acts like a (5,6) array where b[0,:] is broadcast to the other rows,
371
NumPy Reference, Release 2.0.0.dev8464
c acts like a (1,6) array and therefore like a (5,6) array where c[:] is broadcast to every row, and finally,
d acts like a (5,6) array where the single value is repeated.
The output of the ufunc (and its methods) is not necessarily an ndarray, if all input arguments are not ndarrays.
All output arrays will be passed to the __array_prepare__ and __array_wrap__ methods of the in-
put (besides ndarrays, and scalars) that defines it and has the highest __array_priority__ of any other
input to the universal function. The default __array_priority__ of the ndarray is 0.0, and the default
__array_priority__ of a subtype is 1.0. Matrices have __array_priority__ equal to 10.0.
All ufuncs can also take output arguments. If necessary, output will be cast to the data-type(s) of the provided output
array(s). If a class with an __array__ method is used for the output, results will be written to the object returned
by __array__. Then, if the class also has an __array_prepare__ method, it is called so metadata may be
determined based on the context of the ufunc (the context consisting of the ufunc itself, the arguments passed to
the ufunc, and the ufunc domain.) The array object returned by __array_prepare__ is passed to the ufunc for
computation. Finally, if the class also has an __array_wrap__ method, the returned ndarray result will be
passed to that method just before passing control back to the caller.
Internally, buffers are used for misaligned data, swapped data, and data that has to be converted from one data type to
another. The size of internal buffers is settable on a per-thread basis. There can be up to 2(ninputs + noutputs ) buffers
of the specified size created to handle the data from all the inputs and outputs of a ufunc. The default size of a buffer is
10,000 elements. Whenever buffer-based calculation would be needed, but all input arrays are smaller than the buffer
size, those misbehaved or incorrectly-typed arrays will be copied before the calculation proceeds. Adjusting the size of
the buffer may therefore alter the speed at which ufunc calculations of various sorts are completed. A simple interface
for setting this variable is accessible using the function
setbufsize(size) Set the size of the buffer used in ufuncs.
setbufsize(size)
Set the size of the buffer used in ufuncs.
Parameters
size : int
Size of buffer.
Universal functions can trip special floating-point status registers in your hardware (such as divide-by-zero). If avail-
able on your platform, these registers will be regularly checked during calculation. Error handling is controlled on a
per-thread basis, and can be configured using the functions
seterr([all, divide, over, under, invalid]) Set how floating-point errors are handled.
seterrcall(func) Set the floating-point error callback function or log object.
seterr(all=None, divide=None, over=None, under=None, invalid=None)
Set how floating-point errors are handled.
Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by
these settings.
Parameters
all : {ignore, warn, raise, call, print, log}, optional
Set treatment for all types of floating-point errors at once:
ignore: Take no action when the exception occurs.
warn: Print a RuntimeWarning (via the Python warnings module).
raise: Raise a FloatingPointError.
call: Call a function specified using the seterrcall function.
print: Print a warning directly to stdout.
log: Record error in a Log object specified by seterrcall.
The default is not to change the current behavior.
divide : {ignore, warn, raise, call, print, log}, optional
Treatment for division by zero.
over : {ignore, warn, raise, call, print, log}, optional
Treatment for floating-point overflow.
under : {ignore, warn, raise, call, print, log}, optional
Treatment for floating-point underflow.
invalid : {ignore, warn, raise, call, print, log}, optional
Treatment for invalid floating-point operation.
Returns
old_settings : dict
Dictionary containing the old settings.
See Also:
seterrcall
Set a callback function for the call mode.
geterr, geterrcall
Notes
The floating-point exceptions are defined in the IEEE 754 standard [1]:
Division by zero: infinite result obtained from finite numbers.
Overflow: result too large to be expressed.
Underflow: result so close to zero that some precision was lost.
Invalid operation: result is not an expressible number, typically indicates that a NaN was produced.
Examples
seterrcall(func)
Set the floating-point error callback function or log object.
There are two ways to capture floating-point error messages. The first is to set the error-handler to call, using
seterr. Then, set the function to call using this function.
The second is to set the error-handler to log, using seterr. Floating-point errors then trigger a call to the write
method of the provided object.
Parameters
func : callable f(err, flag) or object with write method
Function to call upon floating-point errors (call-mode) or object whose write method
is used to log such message (log-mode).
The call function takes two arguments. The first is the type of error (one of divide,
over, under, or invalid), and the second is the status flag. The flag is a byte, whose
least-significant bits indicate the status:
Examples
Callback upon error:
>>> np.seterrcall(saved_handler)
<function err_handler at 0x...>
>>> np.seterr(**save_err)
{over: call, divide: call, invalid: call, under: call}
>>> np.seterrcall(saved_handler)
<__main__.Log object at 0x...>
>>> np.seterr(**save_err)
{over: log, divide: log, invalid: log, under: log}
At the core of every ufunc is a one-dimensional strided loop that implements the actual function for a specific type
combination. When a ufunc is created, it is given a static list of inner loops and a corresponding list of type signatures
over which the ufunc operates. The ufunc machinery uses this list to determine which inner loop to use for a particular
case. You can inspect the .types attribute for a particular ufunc to see which type combinations have a defined inner
loop and which output type they produce (character codes are used in said output for brevity).
Casting must be done on one or more of the inputs whenever the ufunc does not have a core loop implementation for
the input types provided. If an implementation for the input types cannot be found, then the algorithm searches for an
implementation with a type signature to which all of the inputs can be cast safely. The first one it finds in its internal
list of loops is selected and performed, after all necessary type casting. Recall that internal copies during ufuncs (even
for casting) are limited to the size of an internal buffer (which is user settable).
Note: Universal functions in NumPy are flexible enough to have mixed type signatures. Thus, for example, a universal
function could be defined that works with floating-point and integer values. See ldexp for an example.
By the above description, the casting rules are essentially implemented by the question of when a data type can be
cast safely to another data type. The answer to this question can be determined in Python with a function call:
can_cast(fromtype, totype). The Figure below shows the results of this call for the 21 internally supported
types on the authors 32-bit system. You can generate this table for your system with the code given in the Figure.
Figure
Code segment showing the can cast safely table for a 32-bit system.
You should note that, while included in the table for completeness, the S, U, and V types cannot be operated on
by ufuncs. Also, note that on a 64-bit system the integer types may have different sizes, resulting in a slightly altered
table.
Mixed scalar-array operations use a different set of casting rules that ensure that a scalar cannot upcast an array
unless the scalar is of a fundamentally different kind of data (i.e., under a different hierarchy in the data-type hierarchy)
than the array. This rule enables you to use scalar constants in your code (which, as Python types, are interpreted
accordingly in ufuncs) without worrying about whether the precision of the scalar constant will cause upcasting on
your large (small precision) array.
2.6 ufunc
All ufuncs take optional keyword arguments. These represent rather advanced usage and will not typically be used by
most Numpy users. sig
Either a data-type, a tuple of data-types, or a special signature string indicating the input and output
types of a ufunc. This argument allows you to provide a specific signature for the 1-d loop to use in
the underlying calculation. If the loop specified does not exist for the ufunc, then a TypeError is raised.
Normally, a suitable loop is found automatically by comparing the input types with what is available and
searching for a loop with data-types to which all inputs can be cast safely. This keyword argument lets
you bypass that search and choose a particular loop. A list of available signatures is provided by the types
attribute of the ufunc object.
extobj
a list of length 1, 2, or 3 specifying the ufunc buffer-size, the error mode integer, and the error call-
back function. Normally, these values are looked up in a thread-specific dictionary. Passing them here
circumvents that look up and uses the low-level specification provided for the error mode. This may be
useful, for example, as an optimization for calculations requiring many ufunc calls on small arrays in a
loop.
2.6.2 Attributes
There are some informational attributes that universal functions possess. None of the attributes can be set.
__doc__ A docstring for each ufunc. The first part of the docstring is dynamically generated from the number of
outputs, the name, and the number of inputs. The second part of the docstring is provided at creation
time and stored with the ufunc.
__name__The name of the ufunc.
ufunc.nin The number of inputs.
ufunc.nout The number of outputs.
ufunc.nargs The number of arguments.
ufunc.ntypes The number of types.
ufunc.types Returns a list with types grouped input->output.
ufunc.identity The identity value.
nin
The number of inputs.
Data attribute containing the number of arguments the ufunc treats as input.
Examples
>>> np.add.nin
2
>>> np.multiply.nin
2
>>> np.power.nin
2
>>> np.exp.nin
1
nout
The number of outputs.
Data attribute containing the number of arguments the ufunc treats as output.
Notes
Since all ufuncs can take output arguments, this will always be (at least) 1.
Examples
>>> np.add.nout
1
>>> np.multiply.nout
1
>>> np.power.nout
1
>>> np.exp.nout
1
nargs
The number of arguments.
Data attribute containing the number of arguments the ufunc takes, including optional ones.
Notes
Typically this value will be one more than what you might expect because all ufuncs take the optional out
argument.
Examples
>>> np.add.nargs
3
>>> np.multiply.nargs
3
>>> np.power.nargs
3
>>> np.exp.nargs
2
ntypes
The number of types.
The number of numerical NumPy types - of which there are 18 total - on which the ufunc can operate.
See Also:
numpy.ufunc.types
Examples
>>> np.add.ntypes
18
>>> np.multiply.ntypes
18
>>> np.power.ntypes
17
>>> np.exp.ntypes
7
>>> np.remainder.ntypes
14
types
Returns a list with types grouped input->output.
Data attribute listing the data-type Domain-Range groupings the ufunc can deliver. The data-types are given
using the character codes.
See Also:
numpy.ufunc.ntypes
Examples
>>> np.add.types
[??->?, bb->b, BB->B, hh->h, HH->H, ii->i, II->I, ll->l,
LL->L, qq->q, QQ->Q, ff->f, dd->d, gg->g, FF->F, DD->D,
GG->G, OO->O]
>>> np.multiply.types
[??->?, bb->b, BB->B, hh->h, HH->H, ii->i, II->I, ll->l,
LL->L, qq->q, QQ->Q, ff->f, dd->d, gg->g, FF->F, DD->D,
GG->G, OO->O]
>>> np.power.types
[bb->b, BB->B, hh->h, HH->H, ii->i, II->I, ll->l, LL->L,
qq->q, QQ->Q, ff->f, dd->d, gg->g, FF->F, DD->D, GG->G,
OO->O]
>>> np.exp.types
[f->f, d->d, g->g, F->F, D->D, G->G, O->O]
>>> np.remainder.types
[bb->b, BB->B, hh->h, HH->H, ii->i, II->I, ll->l, LL->L,
qq->q, QQ->Q, ff->f, dd->d, gg->g, OO->O]
identity
The identity value.
Data attribute containing the identity element for the ufunc, if it has one. If it does not, the attribute value is
None.
Examples
>>> np.add.identity
0
>>> np.multiply.identity
1
>>> np.power.identity
1
>>> print np.exp.identity
None
2.6.3 Methods
All ufuncs have four methods. However, these methods only make sense on ufuncs that take two input arguments
and return one output argument. Attempting to call these methods on other ufuncs will cause a ValueError. The
reduce-like methods all take an axis keyword and a dtype keyword, and the arrays must all have dimension >= 1.
The axis keyword specifies the axis of the array over which the reduction will take place and may be negative, but
must be an integer. The dtype keyword allows you to manage a very common problem that arises when naively using
{op}.reduce. Sometimes you may have an array of a certain data type and wish to add up all of its elements, but
the result does not fit into the data type of the array. This commonly happens if you have an array of single-byte
integers. The dtype keyword allows you to alter the data type over which the reduction takes place (and therefore
the type of the output). Thus, you can ensure that the output is a data type with precision large enough to handle
your output. The responsibility of altering the reduce type is mostly up to you. There is one exception: if no
dtype is given for a reduction on the add or multiply operations, then if the input type is an integer (or Boolean)
data-type and smaller than the size of the int_ data type, it will be internally upcast to the int_ (or uint) data-type.
ufunc.reduce(a[, axis, dtype, out]) Reduces as dimension by one, by applying ufunc along one axis.
ufunc.accumulate(array[, axis, dtype, out]) Accumulate the result of applying the operator to all elements.
ufunc.reduceat(a, indices[, axis, dtype, out]) Performs a (local) reduce with specified slices over a single axis.
ufunc.outer(A, B) Apply the ufunc op to all pairs (a, b) with a in A and b in B.
reduce(a, axis=0, dtype=None, out=None)
Reduces as dimension by one, by applying ufunc along one axis.
Let a.shape = (N0 , ..., Ni , ..., NM 1 ). Then uf unc.reduce(a, axis = i)[k0 , .., ki1 , ki+1 , .., kM 1 ] = the
result of iterating j over range(Ni ), cumulatively applying ufunc to each a[k0 , .., ki1 , j, ki+1 , .., kM 1 ]. For a
one-dimensional array, reduce produces results equivalent to:
r = op.identity # op = ufunc
for i in xrange(len(A)):
r = op(r, A[i])
return r
Examples
>>> np.multiply.reduce([2,3,5])
30
>>> X = np.arange(8).reshape((2,2,2))
>>> X
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.add.reduce(X, 0)
array([[ 4, 6],
[ 8, 10]])
>>> np.add.reduce(X) # confirm: default axis value is 0
array([[ 4, 6],
[ 8, 10]])
>>> np.add.reduce(X, 1)
array([[ 2, 4],
[10, 12]])
>>> np.add.reduce(X, 2)
array([[ 1, 5],
[ 9, 13]])
r = np.empty(len(A))
t = op.identity # op = the ufunc being applied to As elements
for i in xrange(len(A)):
t = op(t, A[i])
r[i] = t
return r
Examples
1-D array examples:
>>> I = np.eye(2)
>>> I
array([[ 1., 0.],
[ 0., 1.]])
>>> np.add.accumulate(I, 0)
array([[ 1., 0.],
[ 1., 1.]])
>>> np.add.accumulate(I) # no axis specified = axis zero
array([[ 1., 0.],
[ 1., 1.]])
>>> np.add.accumulate(I, 1)
array([[ 1., 1.],
[ 0., 1.]])
The type used to represent the intermediate results. Defaults to the data type of the
output array if this is provided, or the data type of the input array if no output array is
provided.
out : ndarray, optional
A location into which the result is stored. If not provided a freshly-allocated array is
returned.
Returns
r : ndarray
The reduced values. If out was supplied, r is a reference to out.
Notes
A descriptive example:
If a is 1-D, the function ufunc.accumulate(a) is the same as ufunc.reduceat(a, indices)[::2]
where indices is range(len(array) - 1) with a zero placed in every other element: indices =
zeros(2 * len(a) - 1), indices[1::2] = range(1, len(a)).
Dont be fooled by this attributes name: reduceat(a) is not necessarily smaller than a.
Examples
To take the running sum of four successive values:
A 2-D example:
# reduce such that the result has the following five rows:
# [row1 + row2 + row3]
# [row4]
# [row2]
# [row3]
# [row1 + row2 + row3 + row4]
outer(A, B)
Apply the ufunc op to all pairs (a, b) with a in A and b in B.
Let M = A.ndim, N = B.ndim. Then the result, C, of op.outer(A, B) is an array of dimension M + N
such that:
r = empty(len(A),len(B))
for i in xrange(len(A)):
for j in xrange(len(B)):
r[i,j] = op(A[i], B[j]) # op = ufunc in question
Parameters
A : array_like
First array
B : array_like
Second array
Returns
r : ndarray
Output array
See Also:
numpy.outer
Examples
A multi-dimensional example:
array([[[[ 1, 2, 3, 4]],
[[ 2, 4, 6, 8]],
[[ 3, 6, 9, 12]]],
[[[ 4, 8, 12, 16]],
[[ 5, 10, 15, 20]],
[[ 6, 12, 18, 24]]]])
Warning: A reduce-like operation on an array with a data-type that has a range too small to handle the result
will silently wrap. One should use dtype to increase the size of the data-type over which reduction takes place.
There are currently more than 60 universal functions defined in numpy on one or more types, covering a wide variety
of operations. Some of these ufuncs are called automatically on arrays when the relevant infix notation is used (e.g.,
add(a, b) is called internally when a + b is written and a or b is an ndarray). Nevertheless, you may still want
to use the ufunc call in order to use the optional output argument(s) to place the output(s) in an object (or objects) of
your choice.
Recall that each ufunc operates element-by-element. Therefore, each ufunc will be described as if acting on a set of
scalar inputs to return a set of scalar outputs.
Note: The ufunc still returns its output(s) even if you use the optional output argument(s).
All trigonometric functions use radians when an angle is called for. The ratio of degrees to radians is 180 /.
These function all require integer arguments and they manipulate the bit-pattern of those arguments.
bitwise_and(x1) Compute the bit-wise AND of two arrays element-wise.
bitwise_or(x1) Compute the bit-wise OR of two arrays element-wise.
bitwise_xor(x1) Compute the bit-wise XOR of two arrays element-wise.
invert() Compute bit-wise inversion, or bit-wise NOT, element-wise.
left_shift(x1) Shift the bits of an integer to the left.
right_shift(x1) Shift the bits of an integer to the right.
Warning: Do not use the Python keywords and and or to combine logical array expressions. These keywords
will test the truth value of the entire array (not element-by-element as you might expect). Use the bitwise operators
& and | instead.
Warning: The bit-wise operators & and | are the proper way to perform element-by-element array comparisons.
Be sure you understand the operator precedence: (a > 2) & (a < 5) is the proper syntax because a > 2
& a < 5 will result in an error due to the fact that 2 & a is evaluated first.
Tip: The Python function max() will find the maximum over a one-dimensional array, but it will do so using a
slower sequence interface. The reduce method of the maximum ufunc is much faster. Also, the max() method will
not give answers you might expect for arrays with greater than one dimension. The reduce method of minimum also
allows you to compute a total minimum over an array.
minimum(x1) Element-wise minimum of array elements.
Warning: the behavior of maximum(a, b) is different than that of max(a, b). As a ufunc, maximum(a,
b) performs an element-by-element comparison of a and b and chooses each element of the result according to
which element in the two arrays is larger. In contrast, max(a, b) treats the objects a and b as a whole, looks at
the (total) truth value of a > b and uses it to return either a or b (as a whole). A similar difference exists between
minimum(a, b) and min(a, b).
Recall that all of these functions work element-by-element over an array, returning an array output. The description
details only a single operation.
isreal(x) Returns a bool array, where True if input element is real.
iscomplex(x) Returns a bool array, where True if input element is complex.
isfinite() Test element-wise for finite-ness (not infinity or not Not a Number).
isinf() Test element-wise for positive or negative infinity, return result as bool array.
isnan() Test element-wise for Not a Number (NaN), return result as a bool array.
signbit() Returns element-wise True where signbit is set (less than zero).
copysign(x1) Change the sign of x1 to that of x2, element-wise.
nextafter(x1) Return the next representable floating-point value after x1 in the direction of x2 element-wise.
modf(out1) Return the fractional and integral parts of an array, element-wise.
ldexp(x1) Compute y = x1 * 2**x2.
frexp(out1) Split the number, x, into a normalized fraction (y1) and exponent (y2)
fmod(x1) Return the element-wise remainder of division.
floor() Return the floor of the input, element-wise.
ceil() Return the ceiling of the input, element-wise.
trunc() Return the truncated value of the input, element-wise.
THREE
ROUTINES
In this chapter routine docstrings are presented, grouped by functionality. Many docstrings contain example code,
which demonstrates basic usage of the routine. The examples assume that NumPy is imported with:
A convenient way to execute examples is the %doctest_mode mode of IPython, which allows for pasting of multi-
line examples and preserves indentation.
See Also:
Array creation (in NumPy User Guide)
empty(shape[, dtype, order]) Return a new array of given shape and type, without initializing entries.
empty_like(a) Return a new array with the same shape and type as a given array.
eye(N[, M, k, dtype]) Return a 2-D array with ones on the diagonal and zeros elsewhere.
identity(n[, dtype]) Return the identity array.
ones(shape[, dtype, order]) Return a new array of given shape and type, filled with ones.
ones_like() Returns an array of ones with the same shape and type as a given array.
zeros(shape[, dtype, order]) Return a new array of given shape and type, filled with zeros.
zeros_like(a) Return an array of zeros with the same shape and type as a given array.
empty(shape, dtype=float, order=C)
Return a new array of given shape and type, without initializing entries.
Parameters
shape : int or tuple of int
Shape of the empty array
dtype : data-type, optional
Desired output data-type.
order : {C, F}, optional
Whether to store multi-dimensional data in C (row-major) or Fortran (column-major)
order in memory.
389
NumPy Reference, Release 2.0.0.dev8464
See Also:
empty_like, zeros, ones
Notes
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other
hand, it requires the user to manually set all the values in the array, and should be used with caution.
Examples
empty_like(a)
Return a new array with the same shape and type as a given array.
Parameters
a : array_like
The shape and data-type of a define the parameters of the returned array.
Returns
out : ndarray
Array of random data with the same shape and type as a.
See Also:
ones_like
Return an array of ones with shape and type of input.
zeros_like
Return an array of zeros with shape and type of input.
empty
Return a new uninitialized array.
ones
Return a new array setting values to one.
zeros
Return a new array setting values to zero.
Notes
This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be
marginally faster than the functions that do set the array values.
Examples
diag
Return a diagonal 2-D array using a 1-D array specified by the user.
Examples
identity(n, dtype=None)
Return the identity array.
The identity array is a square array with ones on the main diagonal.
Parameters
n : int
Number of rows (and columns) in n x n output.
dtype : data-type, optional
Data-type of the output. Defaults to float.
Returns
out : ndarray
n x n array with its main diagonal set to one, and all other elements 0.
Examples
>>> np.identity(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Examples
>>> np.ones(5)
array([ 1., 1., 1., 1., 1.])
>>> s = (2,2)
>>> np.ones(s)
array([[ 1., 1.],
[ 1., 1.]])
ones_like
Returns an array of ones with the same shape and type as a given array.
Equivalent to a.copy().fill(1).
Please refer to the documentation for zeros_like.
See Also:
zeros_like
Examples
zeros_like
Return an array of zeros with shape and type of input.
ones_like
Return an array of ones with shape and type of input.
empty_like
Return an empty array with shape and type of input.
ones
Return a new array setting values to one.
empty
Return a new uninitialized array.
Examples
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
zeros_like(a)
Return an array of zeros with the same shape and type as a given array.
Equivalent to a.copy().fill(0).
Parameters
a : array_like
The shape and data-type of a define the parameters of the returned array.
Returns
out : ndarray
Array of zeros with same shape and type as a.
See Also:
ones_like
Return an array of ones with shape and type of input.
empty_like
Return an empty array with shape and type of input.
zeros
Return a new array setting values to zero.
ones
Return a new array setting values to one.
empty
Return a new uninitialized array.
Examples
>>> x = np.arange(6)
>>> x = x.reshape((2, 3))
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.zeros_like(x)
array([[0, 0, 0],
[0, 0, 0]])
Examples
Upcasting:
Minimum dimensions 2:
Type provided:
>>> x = np.array([(1,2),(3,4)],dtype=[(a,<i4),(b,<i4)])
>>> x[a]
array([1, 3])
asanyarray
Similar function which passes through subclasses.
ascontiguousarray
Convert input to a contiguous array.
asfarray
Convert input to a floating point ndarray.
asfortranarray
Convert input to an ndarray with column-major memory order.
asarray_chkfinite
Similar function which checks input for NaNs and Infs.
fromiter
Create an array from an iterator.
fromfunction
Construct an array by executing a function on grid positions.
Examples
Convert a list into an array:
>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
False
>>> np.asanyarray(a) is a
True
asarray
Similar function which always returns ndarrays.
ascontiguousarray
Convert input to a contiguous array.
asfarray
Convert input to a floating point ndarray.
asfortranarray
Convert input to an ndarray with column-major memory order.
asarray_chkfinite
Similar function which checks input for NaNs and Infs.
fromiter
Create an array from an iterator.
fromfunction
Construct an array by executing a function on grid positions.
Examples
Convert a list into an array:
>>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])
ascontiguousarray(a, dtype=None)
Return a contiguous array in memory (C order).
Parameters
a : array_like
Input array.
dtype : str or dtype object, optional
Data-type of returned array.
Returns
out : ndarray
Contiguous array of same shape and content as a, with type dtype if specified.
See Also:
asfortranarray
Convert input to an ndarray with column-major memory order.
require
Return an ndarray that satisfies requirements.
ndarray.flags
Information about the memory layout of the array.
Examples
>>> x = np.arange(6).reshape(2,3)
>>> np.ascontiguousarray(x, dtype=np.float32)
array([[ 0., 1., 2.],
[ 3., 4., 5.]], dtype=float32)
>>> x.flags[C_CONTIGUOUS]
True
asmatrix(data, dtype=None)
Interpret the input as a matrix.
Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to
matrix(data, copy=False).
Parameters
data : array_like
Input data.
Returns
mat : matrix
data interpreted as a matrix.
Examples
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
copy(a)
Return an array copy of the given object.
Parameters
a : array_like
Input data.
Returns
arr : ndarray
Array interpretation of a.
Notes
This is equivalent to
Examples
Create an array x, with a reference y and a copy z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
Notes
If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.:
>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder(>)
>>> np.frombuffer(buf, dtype=dt)
The data of the resulting array will not be byteswapped, but will be interpreted correctly.
Examples
Notes
Do not rely on the combination of tofile and fromfile for data storage, as the binary files generated are are not
platform independent. In particular, no byte-order or data-type information is saved. Data can be stored in the
platform independent .npy format using save and load instead.
Examples
Construct an ndarray:
>>> import os
>>> fname = os.tmpnam()
>>> x.tofile(fname)
>>> np.save(fname, x)
>>> np.load(fname + .npy)
array([((10, 0), 98.25)],
dtype=[(time, [(min, <i4), (sec, <i4)]), (temp, <f8)])
Notes
Keywords other than shape and dtype are passed to function.
Examples
Notes
Specify count to improve performance. It allows fromiter to pre-allocate the output array, instead of
resizing it on demand.
Examples
Read this number of dtype elements from the data. If this is negative, then the size will
be determined from the length of the data.
sep : str, optional
If provided and not empty, then the data will be interpreted as ASCII text with decimal
numbers. This argument is interpreted as the string separating numbers in the data.
Extra whitespace between elements is also ignored.
Returns
arr : array
The constructed array.
Raises
ValueError :
If the string is not the correct size to satisfy the requested dtype and count.
Examples
Invalid inputs:
Notes
This function aims to be a fast reader for simply formatted files. The genfromtxt function provides more sophis-
ticated handling of, e.g., lines with missing values.
Examples
>>> from StringIO import StringIO # StringIO behaves like a file object
>>> c = StringIO("0 1\n2 3")
>>> np.loadtxt(c)
array([[ 0., 1.],
[ 2., 3.]])
>>> c = StringIO("1,0,2\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=,, usecols=(0, 2), unpack=True)
>>> x
>>> x1=np.array([1,2,3,4])
>>> x2=np.array([a,dd,xyz,12])
>>> x3=np.array([1.1,2,3,4])
>>> r = np.core.records.fromarrays([x1,x2,x3],names=a,b,c)
>>> print r[1]
(2, dd, 2.0)
>>> x1[1]=34
>>> r.a
array([1, 2, 3, 4])
>>> r=np.core.records.fromrecords([(456,dbe,1.2),(2,de,1.3)],
... names=col1,col2,col3)
>>> print r[0]
(456, dbe, 1.2)
>>> r.col1
array([456, 2])
>>> r.col2
chararray([dbe, de],
dtype=|S3)
>>> import cPickle
>>> print cPickle.loads(cPickle.dumps(r))
[(456, dbe, 1.2) (2, de, 1.3)]
Parameters
obj : array of str or unicode-like
Parameters
obj : array of str or unicode-like
itemsize : int, optional
itemsize is the number of characters per scalar in the resulting array. If itemsize is
None, and obj is an object array or a Python list, the itemsize will be automatically
determined. If itemsize is provided and obj is of type str or unicode, then the obj string
will be chunked into itemsize pieces.
unicode : bool, optional
When true, the resulting chararray can contain Unicode characters, when false only
8-bit characters. If unicode is None and obj is one of the following:
a chararray,
an ndarray of type str or unicode
a Python str or unicode object,
then the unicode setting of the output array will be automatically determined.
order : {C, F}, optional
Specify the order of the array. If order is C (default), then the array will be in C-
contiguous order (last-index varies the fastest). If order is F, then the returned array
will be in Fortran-contiguous order (first-index varies the fastest).
linspace
Evenly spaced numbers with careful handling of endpoints.
ogrid
Arrays of evenly spaced numbers in N-dimensions
mgrid
Grid-shaped arrays of evenly spaced numbers in N-dimensions
Examples
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
arange
Similiar to linspace, but uses a step size (instead of the number of samples).
logspace
Samples uniformly distributed in log space.
Examples
Graphical illustration:
1.0
0.8
0.6
0.4
0.2
0.0
0.2
0.4
0 2 4 6 8 10
base ** stop is the final value of the sequence, unless endpoint is False. In that
case, num + 1 values are spaced over the interval in log-space, of which all but the
last (a sequence of length num) are returned.
num : integer, optional
Number of samples to generate. Default is 50.
endpoint : boolean, optional
If true, stop is the last sample. Otherwise, it is not included. Default is True.
base : float, optional
The base of the log space. The step size between the elements in ln(samples) /
ln(base) (or log_base(samples)) is uniform. Default is 10.0.
Returns
samples : ndarray
num samples, equally spaced on a log scale.
See Also:
arange
Similiar to linspace, with the step size specified instead of the number of samples. Note that, when used
with a float endpoint, the endpoint may or may not be included.
linspace
Similar to logspace, but with the samples uniformly distributed in linear space, instead of log space.
Notes
Logspace is equivalent to the code
Examples
Graphical illustration:
1.0
0.8
0.6
0.4
0.2
0.0
0.2
0.4
1 2 3 4 5 6 7 8 9 10
meshgrid(x, y)
Return coordinate matrices from two coordinate vectors.
Parameters
x, y : ndarray
Two 1-D arrays representing the x and y coordinates of a grid.
Returns
X, Y : ndarray
For vectors x, y with lengths Nx=len(x) and Ny=len(y), return X, Y where X and
Y are (Ny, Nx) shaped arrays with the elements of x and y repeated to fill the matrix
along the first dimension for x, the second for y.
See Also:
index_tricks.mgrid
Construct a multi-dimensional meshgrid using indexing notation.
index_tricks.ogrid
Construct an open multi-dimensional meshgrid using indexing notation.
Examples
[6, 6, 6],
[7, 7, 7]])
mgrid
nd_grid instance which returns a dense multi-dimensional meshgrid.
An instance of numpy.lib.index_tricks.nd_grid which returns an dense (or fleshed out) mesh-grid
when indexed, so that each returned argument has the same shape. The dimensions and number of the output
arrays are equal to the number of indexing dimensions. If the step length is not a complex number, then the stop
is not inclusive.
However, if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted
as specifying the number of points to create between the start and stop values, where the stop value is inclusive.
Returns
mesh-grid ndarrays all of the same dimensions :
See Also:
numpy.lib.index_tricks.nd_grid
class of ogrid and mgrid objects
ogrid
like mgrid but returns open (not fleshed out) mesh grids
r_
array concatenator
Examples
>>> np.mgrid[0:5,0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
>>> np.mgrid[-1:1:5j]
array([-1. , -0.5, 0. , 0.5, 1. ])
ogrid
nd_grid instance which returns an open multi-dimensional meshgrid.
An instance of numpy.lib.index_tricks.nd_grid which returns an open (i.e. not fleshed out) mesh-
grid when indexed, so that only one dimension of each returned array is greater than 1. The dimension and
number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex
number, then the stop is not inclusive.
However, if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted
as specifying the number of points to create between the start and stop values, where the stop value is inclusive.
Returns
mesh-grid ndarrays with only one dimension :math:neq 1 :
See Also:
np.lib.index_tricks.nd_grid
class of ogrid and mgrid objects
mgrid
like ogrid but returns dense (or fleshed out) mesh grids
r_
array concatenator
Examples
diagonal
Return specified diagonals.
diagflat
Create a 2-D array with the flattened input as a diagonal.
trace
Sum along diagonals.
triu
Upper triangle of an array.
tril
Lower triange of an array.
Examples
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
diagflat(v, k=0)
Create a two-dimensional array with the flattened input as a diagonal.
Parameters
v : array_like
Input data, which is flattened and set as the k-th diagonal of the output.
k : int, optional
Diagonal to set. The default is 0.
Returns
out : ndarray
The 2-D output array.
See Also:
diag
Matlab workalike for 1-D and 2-D arrays.
diagonal
Return specified diagonals.
trace
Sum along diagonals.
Examples
>>> np.diagflat([1,2], 1)
array([[0, 1, 0],
[0, 0, 2],
[0, 0, 0]])
Examples
tril(m, k=0)
Lower triangle of an array.
Return a copy of an array with elements above the k-th diagonal zeroed.
Parameters
m : array_like, shape (M, N)
Input array.
k : int
Diagonal above which to zero elements. k = 0 is the main diagonal, k is below it and k
> 0 is above.
Returns
L : ndarray, shape (M, N)
Lower triangle of m, of same shape and data-type as m.
See Also:
triu
Examples
triu(m, k=0)
Upper triangle of an array.
Construct a copy of a matrix with elements below the k-th diagonal zeroed.
Please refer to the documentation for tril.
See Also:
tril
Examples
vander(x, N=None)
Generate a Van der Monde matrix.
The columns of the output matrix are decreasing powers of the input vector. Specifically, the i-th output column
is the input vector to the power of N - i - 1. Such a matrix with a geometric progression in each row is
named Van Der Monde, or Vandermonde matrix, from Alexandre-Theophile Vandermonde.
Parameters
x : array_like
1-D input array.
N : int, optional
Order of (number of columns in) the output. If N is not specified, a square array is
returned (N = len(x)).
Returns
out : ndarray
Van der Monde matrix of order N. The first column is x^(N-1), the second x^(N-2)
and so forth.
References
[R276]
Examples
The determinant of a square Vandermonde matrix is the product of the differences between the values of the
input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
Returns
mat : matrix
data interpreted as a matrix.
Examples
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
Examples
>>> A = np.mat(1 1; 1 1)
>>> B = np.mat(2 2; 2 2)
>>> C = np.mat(3 4; 5 6)
>>> D = np.mat(7 8; 9 0)
[3, 4, 7, 8],
[5, 6, 9, 0]])
reshape(a, newshape[, order]) Gives a new shape to an array without changing its data.
ravel(a[, order]) Return a flattened array.
ndarray.flat A 1-D iterator over the array.
ndarray.flatten([order]) Return a copy of the array collapsed into one dimension.
reshape(a, newshape, order=C)
Gives a new shape to an array without changing its data.
Parameters
a : array_like
Array to be reshaped.
newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the
result will be a 1-D array of that length. One shape dimension can be -1. In this case,
the value is inferred from the length of the array and remaining dimensions.
order : {C, F}, optional
Determines whether the array data should be viewed as in C (row-major) order or FOR-
TRAN (column-major) order.
Returns
reshaped_array : ndarray
This will be a new view object if possible; otherwise, it will be a copy.
See Also:
ndarray.reshape
Equivalent method.
Notes
It is not always possible to change the shape of an array without copying the data. If you want an error to be
raise if the data is copied, you should assign the new shape to the shape attribute of the array:
Examples
ravel(a, order=C)
Return a flattened array.
A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.
Parameters
a : array_like
Input array. The elements in a are read in the order specified by order, and packed as a
1-D array.
order : {C,F}, optional
The elements of a are read in this order. It can be either C for row-major order, or F
for column-major order. By default, row-major order is used.
Returns
1d_array : ndarray
Output of the same dtype as a, and of shape (a.size(),).
See Also:
ndarray.flat
1-D iterator over an array.
ndarray.flatten
1-D array copy of the elements of an array in row-major order.
Notes
In row-major order, the row index varies the slowest, and the column index the quickest. This can be generalized
to multiple dimensions, where row-major order implies that the index along the first axis varies slowest, and the
index along the last quickest. The opposite holds for Fortran-, or column-major, mode.
Examples
If an array is in C-order (default), then ravel is equivalent to reshape(-1):
flat
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Pythons built-in iterator
object.
See Also:
flatten
Return a copy of the array collapsed into one dimension.
flatiter
Examples
An assignment example:
>>> x.flat = 3; x
array([[3, 3, 3],
[3, 3, 3]])
>>> x.flat[[1,4]] = 1; x
array([[3, 1, 3],
[3, 1, 3]])
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is
C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
rollaxis(a, axis[, start]) Roll the specified axis backwards, until it lies in a given position.
swapaxes(a, axis1, axis2) Interchange two axes of an array.
ndarray.T Same as self.transpose(), except that self is returned if self.ndim < 2.
transpose(a[, axes]) Permute the dimensions of an array.
rollaxis(a, axis, start=0)
Roll the specified axis backwards, until it lies in a given position.
Parameters
a : ndarray
Input array.
axis : int
The axis to roll backwards. The positions of the other axes do not change relative to one
another.
start : int, optional
The axis is rolled until it lies before this position.
Returns
res : ndarray
Output array.
See Also:
roll
Roll the elements of an array by a number of positions along a given axis.
Examples
>>> a = np.ones((3,4,5,6))
>>> np.rollaxis(a, 3, 1).shape
(3, 6, 4, 5)
>>> np.rollaxis(a, 2).shape
(5, 3, 4, 6)
>>> np.rollaxis(a, 1, 4).shape
(3, 5, 6, 4)
Examples
>>> x = np.array([[1,2,3]])
>>> np.swapaxes(x,0,1)
array([[1],
[2],
[3]])
>>> x = np.array([[[0,1],[2,3]],[[4,5],[6,7]]])
>>> x
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> np.swapaxes(x,0,2)
array([[[0, 4],
[2, 6]],
[[1, 5],
[3, 7]]])
T
Same as self.transpose(), except that self is returned if self.ndim < 2.
Examples
>>> x = np.array([[1.,2.],[3.,4.]])
>>> x
array([[ 1., 2.],
[ 3., 4.]])
>>> x.T
array([[ 1., 3.],
[ 2., 4.]])
>>> x = np.array([1.,2.,3.,4.])
>>> x
array([ 1., 2., 3., 4.])
>>> x.T
array([ 1., 2., 3., 4.])
transpose(a, axes=None)
Permute the dimensions of an array.
Parameters
a : array_like
Input array.
axes : list of ints, optional
By default, reverse the dimensions, otherwise permute the axes according to the values
given.
Returns
p : ndarray
a with its axes permuted. A view is returned whenever possible.
See Also:
rollaxis
Examples
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
>>> np.transpose(x)
array([[0, 2],
[1, 3]])
An array, or sequence of arrays, each with a.ndim >= 1. Copies are made only if
necessary.
See Also:
atleast_2d, atleast_3d
Examples
>>> np.atleast_1d(1.0)
array([ 1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
atleast_2d(*arys)
View inputs as arrays with at least two dimensions.
Parameters
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays
that already have two or more dimensions are preserved.
Returns
res, res2, ... : ndarray
An array, or tuple of arrays, each with a.ndim >= 2. Copies are avoided where
possible, and views with two or more dimensions are returned.
See Also:
atleast_1d, atleast_3d
Examples
>>> np.atleast_2d(3.0)
array([[ 3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[ 0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True
atleast_3d(*arys)
View inputs as arrays with at least three dimensions.
Parameters
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays
that already have three or more dimensions are preserved.
Returns
res1, res2, ... : ndarray
An array, or tuple of arrays, each with a.ndim >= 3. Copies are avoided where
possible, and views with three or more dimensions are returned. For example, a 1-D
array of shape N becomes a view of shape (1, N, 1). A 2-D array of shape (M, N)
becomes a view of shape (M, N, 1).
See Also:
atleast_1d, atleast_2d
Examples
>>> np.atleast_3d(3.0)
array([[[ 3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x
True
class broadcast()
Produce an object that mimics broadcasting.
Parameters
in1, in2, ... : array_like
Input parameters.
Returns
b : broadcast object
Broadcast the input parameters against one another, and return an object that encapsu-
lates the result. Amongst others, it has shape and nd properties, and may be used as
an iterator.
Examples
Manually adding two vectors, using broadcasting:
>>> x + y
array([[5, 6, 7],
[6, 7, 8],
[7, 8, 9]])
Methods
next x.next() -> the next value, or raise StopIteration
reset
next()
x.next() -> the next value, or raise StopIteration
reset()
broadcast_arrays(*args)
Broadcast any number of arrays against each other.
Parameters
*args : arrays
The arrays to broadcast.
Returns
broadcasted : list of arrays
These arrays are views on the original arrays. They are typically not contiguous. Fur-
thermore, more than one element of a broadcasted array may refer to a single memory
location. If you need to write to the arrays, make copies first.
Examples
>>> x = np.array([[1,2,3]])
>>> y = np.array([[1],[2],[3]])
>>> np.broadcast_arrays(x, y)
[array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]), array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])]
Here is a useful idiom for getting contiguous copies instead of non-contiguous views.
expand_dims(a, axis)
Expand the shape of an array.
Insert a new axis, corresponding to a given position in the array shape.
Parameters
a : array_like
Input array.
axis : int
Position (amongst axes) where new axis is to be inserted.
Returns
res : ndarray
Output array. The number of dimensions is one greater than that of the input array.
See Also:
doc.indexing, atleast_1d, atleast_2d, atleast_3d
Examples
>>> x = np.array([1,2])
>>> x.shape
(2,)
Note that some examples may use None instead of np.newaxis. These are the same objects:
squeeze(a)
Remove single-dimensional entries from the shape of an array.
Parameters
a : array_like
Input data.
Returns
squeezed : ndarray
The input array, but with with all dimensions of length 1 removed. Whenever possible,
a view on a is returned.
Examples
asanyarray
Similar function which passes through subclasses.
ascontiguousarray
Convert input to a contiguous array.
asfarray
Convert input to a floating point ndarray.
asfortranarray
Convert input to an ndarray with column-major memory order.
asarray_chkfinite
Similar function which checks input for NaNs and Infs.
fromiter
Create an array from an iterator.
fromfunction
Construct an array by executing a function on grid positions.
Examples
Convert a list into an array:
>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])
asarray
Similar function which always returns ndarrays.
ascontiguousarray
Convert input to a contiguous array.
asfarray
Convert input to a floating point ndarray.
asfortranarray
Convert input to an ndarray with column-major memory order.
asarray_chkfinite
Similar function which checks input for NaNs and Infs.
fromiter
Create an array from an iterator.
fromfunction
Construct an array by executing a function on grid positions.
Examples
Convert a list into an array:
>>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])
asmatrix(data, dtype=None)
Interpret the input as a matrix.
Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to
matrix(data, copy=False).
Parameters
data : array_like
Input data.
Returns
mat : matrix
data interpreted as a matrix.
Examples
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])
Examples
asfortranarray(a, dtype=None)
Return an array laid out in Fortran order in memory.
Parameters
a : array_like
Input array.
dtype : str or dtype object, optional
By default, the data-type is inferred from the input data.
Returns
out : ndarray
The input a in Fortran, or column-major, order.
See Also:
ascontiguousarray
Convert input to a contiguous (C order) array.
asanyarray
Convert input to an ndarray with either row or column-major memory order.
require
Return an ndarray that satisfies requirements.
ndarray.flags
Information about the memory layout of the array.
Examples
>>> x = np.arange(6).reshape(2,3)
>>> y = np.asfortranarray(x)
>>> x.flags[F_CONTIGUOUS]
False
>>> y.flags[F_CONTIGUOUS]
True
asscalar(a)
Convert an array of size 1 to its scalar equivalent.
Parameters
a : ndarray
Input array of size 1.
Returns
out : scalar
Scalar representation of a. The input data type is preserved.
Examples
>>> np.asscalar(np.array([24]))
24
See Also:
asarray
Convert input to an ndarray.
asanyarray
Convert to an ndarray, but pass through ndarray subclasses.
ascontiguousarray
Convert input to a contiguous array.
asfortranarray
Convert input to an ndarray with column-major memory order.
ndarray.flags
Information about the memory layout of the array.
Notes
The returned array will be guaranteed to have the listed requirements by making a copy if needed.
Examples
>>> x = np.arange(6).reshape(2,3)
>>> x.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
Arrays to stack. All of them must have the same first dimension.
Returns
stacked : 2-D array
The array formed by stacking the given arrays.
See Also:
hstack, vstack, concatenate
Notes
This function is equivalent to np.vstack(tup).T.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
ma.concatenate
Concatenate function that preserves input masks.
array_split
Split an array into multiple sub-arrays of equal or near-equal size.
split
Split array into a list of multiple sub-arrays of equal size.
hsplit
Split array into multiple sub-arrays horizontally (column wise)
vsplit
Split array into multiple sub-arrays vertically (row wise)
dsplit
Split array into multiple sub-arrays along the 3rd axis (depth).
hstack
Stack arrays in sequence horizontally (column wise)
vstack
Stack arrays in sequence vertically (row wise)
dstack
Stack arrays in sequence depth wise (along third dimension)
Notes
When one or more of the arrays to be concatenated is a MaskedArray, this function will return a MaskedArray
object instead of an ndarray, but the input masks are not preserved. In cases where a MaskedArray is expected
as input, use the ma.concatenate function from the masked array module instead.
Examples
>>> a = np.ma.arange(3)
>>> a[1] = np.ma.masked
>>> b = np.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],
mask = [False True False],
fill_value = 999999)
>>> b
array([2, 3, 4])
>>> np.concatenate([a, b])
masked_array(data = [0 1 2 2 3 4],
mask = False,
fill_value = 999999)
>>> np.ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
mask = [False True False False False False],
fill_value = 999999)
dstack(tup)
Stack arrays in sequence depth wise (along third axis).
Takes a sequence of arrays and stack them along the third axis to make a single array. Rebuilds arrays divided
by dsplit. This is a simple way to stack 2D arrays (images) into a single 3D array for processing.
Parameters
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all but the third axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack along first axis.
hstack
Stack along second axis.
concatenate
Join arrays.
dsplit
Split array along third axis.
Notes
Equivalent to np.concatenate(tup, axis=2).
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
hstack(tup)
Stack arrays in sequence horizontally (column wise).
Take a sequence of arrays and stack them horizontally to make a single array. Rebuild arrays divided by hsplit.
Parameters
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third axis).
concatenate
Join a sequence of arrays together.
hsplit
Split array along second axis.
Notes
Equivalent to np.concatenate(tup, axis=1)
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
vstack(tup)
Stack arrays in sequence vertically (row wise).
Take a sequence of arrays and stack them vertically to make a single array. Rebuild arrays divided by vsplit.
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
Equivalent to np.concatenate(tup, axis=0)
Examples
array_split(ary, indices_or_sections[, axis]) Split an array into multiple sub-arrays of equal or near-equal size.
dsplit(ary, indices_or_sections) Split array into multiple sub-arrays along the 3rd axis (depth).
hsplit(ary, indices_or_sections) Split an array into multiple sub-arrays horizontally (column-wise).
split(ary, indices_or_sections[, axis]) Split an array into multiple sub-arrays of equal size.
vsplit(ary, indices_or_sections) Split an array into multiple sub-arrays vertically (row-wise).
array_split(ary, indices_or_sections, axis=0)
Split an array into multiple sub-arrays of equal or near-equal size.
Please refer to the split documentation. The only difference between these functions is that array_split
allows indices_or_sections to be an integer that does not equally divide the axis.
See Also:
split
Split array into multiple sub-arrays of equal size.
Examples
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
dsplit(ary, indices_or_sections)
Split array into multiple sub-arrays along the 3rd axis (depth).
Please refer to the split documentation. dsplit is equivalent to split with axis=2, the array is always split along
the third axis provided the array dimension is greater than or equal to 3.
See Also:
split
Split an array into multiple sub-arrays of equal size.
Examples
>>> x = np.arange(16.0).reshape(2, 2, 4)
>>> x
array([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]])
>>> np.dsplit(x, 2)
hsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays horizontally (column-wise).
Please refer to the split documentation. hsplit is equivalent to split with axis=1, the array is always split along
the second axis regardless of the array dimension.
See Also:
split
Split an array into multiple sub-arrays of equal size.
Examples
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
[ 4., 5., 6.],
[ 8., 9., 10.],
[ 12., 13., 14.]]),
array([[ 3.],
[ 7.],
[ 11.],
[ 15.]]),
array([], dtype=float64)]
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0., 1.]],
[[ 4., 5.]]]),
array([[[ 2., 3.]],
[[ 6., 7.]]])]
array_split
Split an array into multiple sub-arrays of equal or near-equal size. Does not raise an exception if an equal
division cannot be made.
hsplit
Split array into multiple sub-arrays horizontally (column-wise).
vsplit
Split array into multiple sub-arrays vertically (row wise).
dsplit
Split array into multiple sub-arrays along the 3rd axis (depth).
concatenate
Join arrays together.
hstack
Stack arrays in sequence horizontally (column wise).
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
Examples
>>> x = np.arange(9.0)
>>> np.split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7., 8.])]
>>> x = np.arange(8.0)
>>> np.split(x, [3, 5, 6, 10])
[array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]
vsplit(ary, indices_or_sections)
Split an array into multiple sub-arrays vertically (row-wise).
Please refer to the split documentation. vsplit is equivalent to split with axis=0 (default), the array is
always split along the first axis regardless of the array dimension.
See Also:
split
Split an array into multiple sub-arrays of equal size.
Examples
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.vsplit(x, 2)
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]]),
array([[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])]
>>> np.vsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]]),
With a higher dimensional array the split is still along the first axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.vsplit(x, 2)
[array([[[ 0., 1.],
[ 2., 3.]]]),
array([[[ 4., 5.],
[ 6., 7.]]])]
tile(A, reps) Construct an array by repeating A the number of times given by reps.
repeat(a, repeats[, axis]) Repeat elements of an array.
tile(A, reps)
Construct an array by repeating A the number of times given by reps.
If reps has length d, the result will have dimension of max(d, A.ndim).
If A.ndim < d, A is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted
to (1, 3) for 2-D replication, or shape (1, 1, 3) for 3-D replication. If this is not the desired behavior, promote A
to d-dimensions manually before calling this function.
If A.ndim > d, reps is promoted to A.ndim by pre-pending 1s to it. Thus for an A of shape (2, 3, 4, 5), a reps
of (2, 2) is treated as (1, 1, 2, 2).
Parameters
A : array_like
The input array.
reps : array_like
The number of repetitions of A along each axis.
Returns
c : ndarray
The tiled output array.
See Also:
repeat
Repeat elements of an array.
Examples
tile
Tile an array.
Examples
>>> x = np.array([[1,2],[3,4]])
>>> np.repeat(x, 2)
array([1, 1, 2, 2, 3, 3, 4, 4])
>>> np.repeat(x, 3, axis=1)
array([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
>>> np.repeat(x, [1, 2], axis=0)
array([[1, 2],
[3, 4],
[3, 4]])
delete(arr, obj[, axis]) Return a new array with sub-arrays along an axis deleted.
insert(arr, obj, values[, axis]) Insert values along the given axis before the given indices.
append(arr, values[, axis]) Append values to the end of an array.
resize(a, new_shape) Return a new array with the specified shape.
trim_zeros(filt[, trim]) Trim the leading and/or trailing zeros from a 1-D array or sequence.
unique(ar[, return_index, return_inverse]) Find the unique elements of an array.
delete(arr, obj, axis=None)
Return a new array with sub-arrays along an axis deleted.
Parameters
arr : array_like
Input array.
obj : slice, int or array of ints
Indicate which sub-arrays to remove.
axis : int, optional
The axis along which to delete the subarray defined by obj. If axis is None, obj is
applied to the flattened array.
Returns
out : ndarray
A copy of arr with the elements specified by obj removed. Note that delete does not
occur in-place. If axis is None, out is a flattened array.
See Also:
insert
Insert elements into an array.
append
Append elements at the end of an array.
Examples
Parameters
arr : array_like
Input array.
obj : int, slice or sequence of ints
Object that defines the index or indices before which values is inserted.
values : array_like
Values to insert into arr. If the type of values is different from that of arr, values is
converted to the type of arr.
axis : int, optional
Axis along which to insert values. If axis is None then arr is flattened first.
Returns
out : ndarray
A copy of arr with values inserted. Note that insert does not occur in-place: a new array
is returned. If axis is None, out is a flattened array.
See Also:
append
Append elements at the end of an array.
delete
Delete elements from an array.
Examples
>>> b = a.flatten()
>>> b
array([1, 1, 2, 2, 3, 3])
>>> np.insert(b, [2, 2], [5, 6])
array([1, 1, 5, 6, 2, 2, 3, 3])
>>> x = np.arange(8).reshape(2, 4)
>>> idx = (1, 3)
>>> np.insert(x, idx, 999, axis=1)
array([[ 0, 999, 1, 2, 999, 3],
[ 4, 999, 5, 6, 999, 7]])
insert
Insert elements into an array.
delete
Delete elements from an array.
Examples
resize(a, new_shape)
Return a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled with repeated copied of a. Note that
this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.
Parameters
a : array_like
Array to be resized.
new_shape : {tuple, int}
Shape of resized array.
Returns
reshaped_array : ndarray
The new array is formed from the data in the old array, repeated if necessary to fill out
the required number of elements. The data are repeated in the order that the data are
stored in memory.
See Also:
ndarray.resize
resize an array in-place.
Examples
>>> a=np.array([[0,1],[2,3]])
>>> np.resize(a,(1,4))
array([[0, 1, 2, 3]])
>>> np.resize(a,(2,4))
array([[0, 1, 2, 3],
[0, 1, 2, 3]])
trim_zeros(filt, trim=fb)
Trim the leading and/or trailing zeros from a 1-D array or sequence.
Parameters
filt : 1-D array or sequence
Input array.
trim : str, optional
A string with f representing trim from front and b to trim from back. Default is fb,
trim zeros from both front and back of the array.
Returns
trimmed : 1-D array or sequence
The result of trimming the input. The input data type is preserved.
Examples
>>> np.trim_zeros(a, b)
array([0, 0, 0, 1, 2, 3, 0, 2, 1])
numpy.lib.arraysetops
Module with a number of other functions for performing set operations on arrays.
Examples
Return the indices of the original array that give the unique values:
array([a, b, c],
dtype=|S1)
flipud
Flip array in the up/down direction.
rot90
Rotate array counterclockwise.
Notes
Equivalent to A[:,::-1]. Does not require the array to be two-dimensional.
Examples
>>> A = np.diag([1.,2.,3.])
>>> A
array([[ 1., 0., 0.],
[ 0., 2., 0.],
[ 0., 0., 3.]])
>>> np.fliplr(A)
array([[ 0., 0., 1.],
[ 0., 2., 0.],
[ 3., 0., 0.]])
>>> A = np.random.randn(2,3,5)
>>> np.all(np.fliplr(A)==A[:,::-1,...])
True
flipud(m)
Flip array in the up/down direction.
Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order
than before.
Parameters
m : array_like
Input array.
Returns
out : array_like
A view of m with the rows reversed. Since a view is returned, this operation is O(1).
See Also:
fliplr
Flip array in the left/right direction.
rot90
Rotate array counterclockwise.
Notes
Equivalent to A[::-1,...]. Does not require the array to be two-dimensional.
Examples
>>> A = np.random.randn(2,3,5)
>>> np.all(np.flipud(A)==A[::-1,...])
True
>>> np.flipud([1,2])
array([2, 1])
Parameters
a : array_like
Array to be reshaped.
newshape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer, then the
result will be a 1-D array of that length. One shape dimension can be -1. In this case,
the value is inferred from the length of the array and remaining dimensions.
order : {C, F}, optional
Determines whether the array data should be viewed as in C (row-major) order or FOR-
TRAN (column-major) order.
Returns
reshaped_array : ndarray
This will be a new view object if possible; otherwise, it will be a copy.
See Also:
ndarray.reshape
Equivalent method.
Notes
It is not always possible to change the shape of an array without copying the data. If you want an error to be
raise if the data is copied, you should assign the new shape to the shape attribute of the array:
Examples
Input array.
shift : int
The number of places by which elements are shifted.
axis : int, optional
The axis along which elements are shifted. By default, the array is flattened before
shifting, after which the original shape is restored.
Returns
res : ndarray
Output array, with the same shape as a.
See Also:
rollaxis
Roll the specified axis backwards, until it lies in a given position.
Examples
>>> x = np.arange(10)
>>> np.roll(x, 2)
array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
rot90(m, k=1)
Rotate an array by 90 degrees in the counter-clockwise direction.
The first two dimensions are rotated; therefore, the array must be at least 2-D.
Parameters
m : array_like
Array of two or more dimensions.
k : integer
Number of times the array is rotated by 90 degrees.
Returns
y : ndarray
Rotated array.
See Also:
fliplr
Flip an array horizontally.
flipud
Flip an array vertically.
Examples
See Also:
Indexing
Examples
r_
Translates slice objects to concatenation along the first axis.
This is a simple way to build up arrays quickly. There are two use cases.
1.If the index expression contains comma separated arrays, then stack them along their first axis.
2.If the index expression contains slice notation or scalars then create a 1-D array with a range indicated by
the slice notation.
If slice notation is used, the syntax start:stop:step is equivalent to np.arange(start, stop,
step) inside of the brackets. However, if step is an imaginary number (i.e. 100j) then its integer
portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words
start:stop:stepj is interpreted as np.linspace(start, stop, step, endpoint=1) inside
of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together.
Optional character strings placed as the first element of the index expression can be used to change the output.
The strings r or c result in matrix output. If the result is 1-D and r is specified a 1 x N (row) matrix is
produced. If the result is 1-D and c is specified, then a N x 1 (column) matrix is produced. If the result is 2-D
then both provide the same matrix result.
A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-
separated integers allows indication of the minimum number of dimensions to force each entry into as the second
integer (the axis to concatenate along is still the first integer).
A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum
number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less
than the specified number of dimensions. In other words the third integer allows you to specify where the 1s
should be placed in the shape of the arrays that have their shapes upgraded. By default, they are placed in the
front of the shape tuple. The third argument allows you to specify where the start of the array should be instead.
Thus, a third argument of 0 would place the 1s at the end of the array shape. Negative integers specify where
in the new shape tuple the last dimension of upgraded arrays should be placed, so the default is -1.
Parameters
Not a function, so takes no parameters :
Returns
A concatenated ndarray or matrix. :
See Also:
concatenate
Join a sequence of arrays together.
c_
Translates slice objects to concatenation along the second axis.
Examples
String integers specify the axis to concatenate along or the minimum number of dimensions to force entries into.
s_
A nicer way to build up index tuples for arrays.
Note: Use one of the two predefined instances index_exp or s_ rather than directly using IndexExpression.
For any index combination, including slicing and axis insertion, a[indices] is the same as
a[np.index_exp[indices]] for any array a. However, np.index_exp[indices] can be used any-
where in Python code and returns a tuple of slice objects that can be used in the construction of complex index
expressions.
Parameters
maketuple : bool
If True, always returns a tuple.
See Also:
index_exp
Predefined instance that always returns a tuple: index_exp = IndexExpression(maketuple=True).
s_
Predefined instance without tuple conversion: s_ = IndexExpression(maketuple=False).
Notes
You can do all this with slice() plus a few special objects, but theres a lot to remember and this version is simpler
because it uses the standard array indexing syntax.
Examples
>>> np.s_[2::2]
slice(2, None, 2)
>>> np.index_exp[2::2]
(slice(2, None, 2),)
nonzero(a)
Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[nonzero(a)]
transpose(nonzero(a))
The result of this is always a 2-D array, with a row for each non-zero element.
Parameters
a : array_like
Input array.
Returns
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also:
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
>>> x = np.eye(3)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> np.nonzero(x)
(array([0, 1, 2]), array([0, 1, 2]))
>>> x[np.nonzero(x)]
array([ 1., 1., 1.])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
Notes
If x and y are given and input arrays are 1-D, where is equivalent to:
Examples
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )] # Note: result is 1D.
array([ 4., 5., 6., 7., 8.])
>>> np.where(x < 5, x, -1) # Note: broadcasting.
array([[ 0., 1., 2.],
[ 3., 4., -1.],
[-1., -1., -1.]])
Notes
The output shape is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if
dimensions is a tuple (r0, ..., rN-1) of length N, the output shape is (N,r0,...,rN-1).
The subarrays grid[k] contains the N-D array of indices along the k-th axis. Explicitly:
grid[k,i0,i1,...,iN-1] = ik
Examples
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
[4, 5, 6]])
Note that it would be more straightforward in the above example to extract the required elements directly with
x[:2, :3].
ix_(*args)
Construct an open mesh from multiple sequences.
This function takes N 1-D sequences and returns N outputs with N dimensions each, such that the shape is 1 in
all but one dimension and the dimension with the non-unit shape value cycles through all N dimensions.
Using ix_ one can quickly construct index arrays that will index the cross product.
a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].
Parameters
args : 1-D sequences
Returns
out : tuple of ndarrays
N arrays with N dimensions each, with N the number of input sequences. Together
these arrays form an open mesh.
See Also:
ogrid, mgrid, meshgrid
Examples
>>> a = np.arange(10).reshape(2, 5)
>>> a
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
>>> ixgrid = np.ix_([0,1], [2,4])
>>> ixgrid
(array([[0],
[1]]), array([[2, 4]]))
>>> ixgrid[0].shape, ixgrid[1].shape
((2, 1), (1, 2))
>>> a[ixgrid]
array([[2, 4],
[7, 9]])
ogrid
nd_grid instance which returns an open multi-dimensional meshgrid.
An instance of numpy.lib.index_tricks.nd_grid which returns an open (i.e. not fleshed out) mesh-
grid when indexed, so that only one dimension of each returned array is greater than 1. The dimension and
number of the output arrays are equal to the number of indexing dimensions. If the step length is not a complex
number, then the stop is not inclusive.
However, if the step length is a complex number (e.g. 5j), then the integer part of its magnitude is interpreted
as specifying the number of points to create between the start and stop values, where the stop value is inclusive.
Returns
mesh-grid ndarrays with only one dimension :math:neq 1 :
See Also:
np.lib.index_tricks.nd_grid
class of ogrid and mgrid objects
mgrid
like ogrid but returns dense (or fleshed out) mesh grids
r_
array concatenator
Examples
unravel_index(x, dims)
Convert a flat index to an index tuple for an array of given shape.
Parameters
x : int
Flattened index.
dims : tuple of ints
Input shape, the shape of an array into which indexing is required.
Returns
idx : tuple of ints
Tuple of the same shape as dims, containing the unraveled index.
Notes
In the Examples section, since arr.flat[x] == arr.max() it may be easier to use flattened indexing
than to re-map the index to a tuple.
Examples
diag_indices(n, ndim=2)
Return the indices to access the main diagonal of an array.
This returns a tuple of indices that can be used to access the main diagonal of an array a with a.ndim >= 2
dimensions and shape (n, n, ..., n). For a.ndim = 2 this is the usual diagonal, for a.ndim > 2 this is the
set of indices to access a[i, i, ..., i] for i = [0..n-1].
Parameters
n : int
The size, along each dimension, of the arrays for which the returned indices can be
used.
ndim : int, optional
The number of dimensions.
See Also:
diag_indices_from
Notes
New in version 1.4.0.
Examples
Create a set of indices to access the diagonal of a (4, 4) array:
>>> di = np.diag_indices(4)
>>> di
(array([0, 1, 2, 3]), array([0, 1, 2, 3]))
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> a[di] = 100
>>> a
array([[100, 1, 2, 3],
[ 4, 100, 6, 7],
[ 8, 9, 100, 11],
[ 12, 13, 14, 100]])
>>> d3 = np.diag_indices(2, 3)
>>> d3
(array([0, 1]), array([0, 1]), array([0, 1]))
[0, 0]],
[[0, 0],
[0, 1]]])
diag_indices_from(arr)
Return the indices to access the main diagonal of an n-dimensional array.
See diag_indices for full details.
Parameters
arr : array, at least 2-D
See Also:
diag_indices
Notes
New in version 1.4.0.
mask_indices(n, mask_func, k=0)
Return the indices to access (n, n) arrays, given a masking function.
Assume mask_func is a function that, for a square array a of size (n, n) with a possible offset argument k,
when called as mask_func(a, k) returns a new array with zeros in certain locations (functions like triu or
tril do precisely this). Then this function returns the indices where the non-zero values would be located.
Parameters
n : int
The returned indices will be valid to access arrays of shape (n, n).
mask_func : callable
A function whose call signature is similar to that of triu, tril. That is, mask_func(x,
k) returns a boolean array, shaped like x. k is an optional argument to the function.
k : scalar
An optional argument which is passed through to mask_func. Functions like triu, tril
take a second argument that is interpreted as an offset.
Returns
indices : tuple of arrays.
The n arrays of indices corresponding to the locations where
mask_func(np.ones((n, n)), k) is True.
See Also:
triu, tril, triu_indices, tril_indices
Notes
New in version 1.4.0.
Examples
These are the indices that would allow you to access the upper triangular part of any 3x3 array:
>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> a[iu]
array([0, 1, 2, 4, 5, 8])
An offset can be passed also to the masking function. This gets us the indices starting on the first diagonal right
of the main one:
>>> a[iu1]
array([1, 2, 5])
tril_indices(n, k=0)
Return the indices for the lower-triangle of an (n, n) array.
Parameters
n : int
Sets the size of the arrays for which the returned indices will be valid.
k : int, optional
Diagonal offset (see tril for details).
Returns
inds : tuple of arrays
The indices for the triangle. The returned tuple contains two arrays, each with the
indices along one dimension of the array.
See Also:
triu_indices
similar function, for upper-triangular.
mask_indices
generic function accepting an arbitrary mask function.
tril, triu
Notes
New in version 1.4.0.
Examples
Compute two different sets of indices to access 4x4 arrays, one for the lower triangular part starting at the main
diagonal, and one starting two diagonals further right:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> a[il1]
array([ 0, 4, 5, 8, 9, 10, 12, 13, 14, 15])
>>> a[il1] = -1
>>> a
array([[-1, 1, 2, 3],
[-1, -1, 6, 7],
[-1, -1, -1, 11],
[-1, -1, -1, -1]])
These cover almost the whole array (two diagonals right of the main one):
tril_indices_from(arr, k=0)
Return the indices for the lower-triangle of an (n, n) array.
See tril_indices for full details.
Parameters
n : int
Sets the size of the arrays for which the returned indices will be valid.
k : int, optional
Diagonal offset (see tril for details).
See Also:
tril_indices, tril
Notes
New in version 1.4.0.
triu_indices(n, k=0)
Return the indices for the upper-triangle of an (n, n) array.
Parameters
n : int
Sets the size of the arrays for which the returned indices will be valid.
k : int, optional
tril_indices
similar function, for lower-triangular.
mask_indices
generic function accepting an arbitrary mask function.
triu, tril
Notes
New in version 1.4.0.
Examples
Compute two different sets of indices to access 4x4 arrays, one for the upper triangular part starting at the main
diagonal, and one starting two diagonals further right:
>>> a = np.arange(16).reshape(4, 4)
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> a[iu1]
array([ 0, 1, 2, 3, 5, 6, 7, 10, 11, 15])
>>> a[iu1] = -1
>>> a
array([[-1, -1, -1, -1],
[ 4, -1, -1, -1],
[ 8, 9, -1, -1],
[12, 13, 14, -1]])
These cover only a small part of the whole array (two diagonals right of the main one):
triu_indices_from(arr, k=0)
Return the indices for the upper-triangle of an (n, n) array.
See triu_indices for full details.
Parameters
n : int
Sets the size of the arrays for which the returned indices will be valid.
k : int, optional
Diagonal offset (see triu for details).
See Also:
triu_indices, triu
Notes
New in version 1.4.0.
take(a, indices[, axis, out, mode]) Take elements from an array along an axis.
choose(a, choices[, out, mode]) Construct an array from an index array and a set of arrays to choose from.
compress(condition, a[, axis, out]) Return selected slices of an array along given axis.
diag(v[, k]) Extract a diagonal or construct a diagonal array.
diagonal(a[, offset, axis1, axis2]) Return specified diagonals.
select(condlist, choicelist[, default]) Return an array drawn from elements in choicelist, depending on conditions.
take(a, indices, axis=None, out=None, mode=raise)
Take elements from an array along an axis.
This function does the same thing as fancy indexing (indexing arrays using arrays); however, it can be easier
to use if you need elements along a given axis.
Parameters
a : array_like
The source array.
indices : array_like
The indices of the values to extract.
axis : int, optional
The axis over which to select values. By default, the flattened input array is used.
out : ndarray, optional
If provided, the result will be placed in this array. It should be of the appropriate shape
and dtype.
mode : {raise, wrap, clip}, optional
Specifies how out-of-bounds indices will behave.
ndarray.take
equivalent method
Examples
>>> a = [4, 3, 5, 7, 6, 8]
>>> indices = [0, 1, 4]
>>> np.take(a, indices)
array([4, 3, 6])
>>> a = np.array(a)
>>> a[indices]
array([4, 3, 6])
Parameters
a : int array
This array must contain integers in [0, n-1], where n is the number of choices, unless
mode=wrap or mode=clip, in which cases any integers are permissible.
choices : sequence of arrays
Choice arrays. a and all of the choices must be broadcastable to the same shape. If
choices is itself an array (not recommended), then its outermost dimension (i.e., the one
corresponding to choices.shape[0]) is taken as defining the sequence.
out : array, optional
If provided, the result will be inserted into this array. It should be of the appropriate
shape and dtype.
mode : {raise (default), wrap, clip}, optional
Specifies how indices outside [0, n-1] will be treated:
raise : an exception is raised
wrap : value becomes value mod n
clip : values < 0 are mapped to 0, values > n-1 are mapped to n-1
Returns
merged_array : array
The merged result.
Raises
ValueError: shape mismatch :
If a and each choice array are not all broadcastable to the same shape.
See Also:
ndarray.choose
equivalent method
Notes
To reduce the chance of misinterpretation, even though the following abuse is nominally supported, choices
should neither be, nor be thought of as, a single array, i.e., the outermost sequence-like container should be
either a list or a tuple.
Examples
Examples
Working on the flattened array does not return slices along an axis but selects elements.
diag(v, k=0)
Extract a diagonal or construct a diagonal array.
Parameters
v : array_like
If v is a 2-D array, return a copy of its k-th diagonal. If v is a 1-D array, return a 2-D
array with v on the k-th diagonal.
k : int, optional
Diagonal in question. The default is 0. Use k>0 for diagonals above the main diagonal,
and k for diagonals below the main diagonal.
Returns
out : ndarray
The extracted diagonal or constructed diagonal array.
See Also:
diagonal
Return specified diagonals.
diagflat
Create a 2-D array with the flattened input as a diagonal.
trace
Sum along diagonals.
triu
Upper triangle of an array.
tril
Lower triange of an array.
Examples
>>> x = np.arange(9).reshape((3,3))
>>> x
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 8]])
diag
Matlab workalike for 1-D and 2-D arrays.
diagflat
Create diagonal arrays.
trace
Sum along diagonals.
Examples
>>> a = np.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a.diagonal()
array([0, 3])
>>> a.diagonal(1)
array([1])
>>> a = np.arange(8).reshape(2,2,2)
>>> a
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> a.diagonal(0,-2,-1)
array([[0, 3],
[4, 7]])
where
Return elements from one of two arrays depending on condition.
Examples
>>> x = np.arange(10)
>>> condlist = [x<3, x>5]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist)
array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81])
place(arr, mask, vals) Change elements of an array based on conditional and input values.
put(a, ind, v[, mode]) Replaces specified elements of an array with given values.
putmask(a, mask, values) Changes elements of an array based on conditional and input values.
fill_diagonal(a, val) Fill the main diagonal of the given array of any dimensionality.
place(arr, mask, vals)
Change elements of an array based on conditional and input values.
Similar to np.putmask(a, mask, vals), the difference is that place uses the first N elements of vals,
where N is the number of True values in mask, while putmask uses the elements where mask is True.
Note that extract does the exact opposite of place.
Parameters
a : array_like
Array to put data into.
mask : array_like
Boolean mask array. Must have the same size as a.
vals : 1-D sequence
Values to put into a. Only the first N elements are used, where N is the number of True
values in mask. If vals is smaller than N it will be repeated.
See Also:
putmask, put, take, extract
Examples
>>> x = np.arange(6).reshape(2, 3)
>>> np.place(x, x>2, [44, 55])
>>> x
array([[ 0, 1, 2],
[44, 55, 44]])
a.flat[ind] = v
Parameters
a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to place in a at target indices. If v is shorter than ind it will be repeated as
necessary.
mode : {raise, wrap, clip}, optional
Specifies how out-of-bounds indices will behave.
raise raise an error (default)
wrap wrap around
clip clip to the range
clip mode means that all indices that are too large are replaced by the index that ad-
dresses the last element along that axis. Note that this disables indexing with negative
numbers.
See Also:
putmask, place
Examples
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44, 1, -55, 3, 4])
>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode=clip)
>>> a
array([ 0, 1, 2, 3, -5])
See Also:
place, put, take
Examples
>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0, 1, 2],
[ 9, 16, 25]])
>>> x = np.arange(5)
>>> np.putmask(x, x>1, [-33, -44])
>>> x
array([ 0, 1, -33, -44, -33])
fill_diagonal(a, val)
Fill the main diagonal of the given array of any dimensionality.
For an array a with a.ndim > 2, the diagonal is the list of locations with indices a[i, i, ..., i] all
identical. This function modifies the input array in-place, it does not return a value.
Parameters
a : array, at least 2-D.
Array whose diagonal is to be filled, it gets modified in-place.
val : scalar
Value to be written on the diagonal, its type must be compatible with that of the array a.
See Also:
diag_indices, diag_indices_from
Notes
New in version 1.4.0. This functionality can be obtained via diag_indices, but internally this version uses a
much faster implementation that never constructs the indices and uses simple slicing.
Examples
>>> a[0, 0]
array([[4, 0, 0],
[0, 0, 0],
[0, 0, 0]])
>>> a[1, 1]
array([[0, 0, 0],
[0, 4, 0],
[0, 0, 0]])
>>> a[2, 2]
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 4]])
Examples
Methods
next() Standard iterator method, returns the index tuple and array value.
next()
Standard iterator method, returns the index tuple and array value.
Returns
coords : tuple of ints
The indices of the current iteration.
val : scalar
The array element of the current iteration.
class ndindex(*args)
An N-dimensional iterator object to index arrays.
Given the shape of an array, an ndindex instance iterates over the N-dimensional index of the array. At each
iteration a tuple of indices is returned, the last dimension is iterated over first.
Parameters
*args : ints
The size of each dimension of the array.
See Also:
ndenumerate, flatiter
Examples
Methods
ndincr() Increment the multi-dimensional index by one.
next() Standard iterator method, updates the index and returns the index tuple.
ndincr()
Increment the multi-dimensional index by one.
ndincr takes care of the wrapping around of the axes. It is called by ndindex.next and not normally used
directly.
next()
Standard iterator method, updates the index and returns the index tuple.
Returns
val : tuple of ints
Returns a tuple containing the indices of the current iteration.
class flatiter()
Flat iterator object to iterate over arrays.
A flatiter iterator is returned by x.flat for any array x. It allows iterating over the array as if it were a 1-D
array, either in a for-loop or by calling its next method.
Iteration is done in C-contiguous style, with the last index varying the fastest. The iterator can also be indexed
using basic slicing or advanced indexing.
See Also:
ndarray.flat
Return a flat iterator over an array.
ndarray.flatten
Returns a flattened copy of an array.
Notes
A flatiter iterator can not be constructed directly from Python code by calling the flatiter constructor.
Examples
>>> x = np.arange(6).reshape(2, 3)
>>> fl = x.flat
>>> type(fl)
<type numpy.flatiter>
>>> for item in fl:
... print item
...
0
1
2
3
4
5
>>> fl[2:4]
array([2, 3])
Methods
copy() Get a copy of the iterator as a 1-D array.
next x.next() -> the next value, or raise StopIteration
copy()
Get a copy of the iterator as a 1-D array.
Examples
>>> x = np.arange(6).reshape(2, 3)
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> fl = x.flat
>>> fl.copy()
array([0, 1, 2, 3, 4, 5])
next()
x.next() -> the next value, or raise StopIteration
can_cast(fromtype, totype) Returns True if cast between data types can occur without losing precision.
common_type(*arrays) Return a scalar type which is common to the input arrays.
obj2sctype(rep[, default])
can_cast(fromtype, totype)
Returns True if cast between data types can occur without losing precision.
Parameters
fromtype : dtype or dtype specifier
Examples
common_type(*arrays)
Return a scalar type which is common to the input arrays.
The return type will always be an inexact (i.e. floating point) scalar type, even if all the arrays are integer arrays.
If one of the inputs is an integer array, the minimum precision type that is returned is a 64-bit floating point
dtype.
All input arrays can be safely cast to the returned dtype without loss of information.
Parameters
array1, array2, ... : ndarrays
Input arrays.
Returns
out : data type code
Data type code.
See Also:
dtype, mintypecode
Examples
obj2sctype(rep, default=None)
Examples
Using array-scalar type:
>>> np.dtype(np.int16)
dtype(int16)
Record, one field named f1, in itself containing a record with one field:
Record, two fields: the first field contains an unsigned int, the second an int32:
>>> np.dtype([(a,f8),(b,S10)])
dtype([(a, <f8), (b, |S10)])
Using tuples. int is a fixed type, 3 the fields shape. void is a flexible type, here of size 10:
>>> np.dtype([(hello,(np.int,3)),(world,np.void,10)])
dtype([(hello, <i4, 3), (world, |V10)])
Subdivide int16 into 2 int8s, called x and y. 0 and 1 are the offsets in bytes:
>>> np.dtype({surname:(S25,0),age:(np.uint8,25)})
dtype([(surname, |S25), (age, |u1)])
Methods
newbyteorder([new_order]) Return a new dtype with a different byte order.
newbyteorder(new_order=S)
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
Parameters
new_order : string, optional
Byte order to force; a value from the byte order specifications below. The default value
(S) results in swapping the current byte order. new_order codes can be any of:
The code does a case-insensitive check on the first letter of new_order for these alterna-
tives. For example, any of > or B or b or brian are valid to specify big-endian.
Returns
new_dtype : dtype
New dtype object with the given change to the byte order.
Notes
Changes are also made in all fields and sub-arrays of the data type.
Examples
Examples
names and/or titles can be empty lists. If titles is an empty list, titles will simply not appear. If names is empty,
default field names will be used.
Attributes
dtype dtype The converted data-type.
MachAr
The implementation of the tests that produce this information.
iinfo
The equivalent for integer data types.
Notes
For developers of NumPy: do not instantiate this at the module level. The initial calculation of these parameters
is expensive and negatively impacts import times. These objects are cached, so calling finfo() repeatedly
inside your functions is not a problem.
Attributes
eps floating point number of the The smallest representable number such that 1.0 + eps !=
appropriate type 1.0.
epsneg floating point number of the The smallest representable number such that 1.0 - epsneg !=
appropriate type 1.0.
iexp int The number of bits in the exponent portion of the floating point
representation.
machar MachAr The object which calculated these parameters and holds more
detailed information.
machep int The exponent that yields eps.
max floating point number of the The largest representable number.
appropriate type
max- int The smallest positive power of the base (2) that causes overflow.
exp
min floating point number of the The smallest representable number, typically -max.
appropriate type
min- int The most negative power of the base (2) consistent with there being
exp no leading 0s in the mantissa.
negep int The exponent that yields epsneg.
nexp int The number of bits in the exponent including its sign and bias.
nmant int The number of bits in the mantissa.
preci- int The approximate number of decimal digits to which this kind of float
sion is precise.
resolu- floating point number of the The approximate decimal resolution of this type, i.e.
tion appropriate type 10**-precision.
tiny floating point number of the The smallest-magnitude usable number.
appropriate type
class iinfo(type)
Machine limits for integer types.
Parameters
type : integer type, dtype, or instance
The kind of integer data type to get information about.
See Also:
finfo
The equivalent for floating point data types.
Examples
With types:
With instances:
Attributes
min
max
min
max
finfo
Machine limits for floating point types.
iinfo
Machine limits for integer types.
References
[R1]
Attributes
ibeta int Radix in which numbers are represented.
it int Number of base-ibeta digits in the floating point mantissa M.
machep int Exponent of the smallest (most negative) power of ibeta that, added to 1.0, gives something
different from 1.0
eps float Floating-point number beta**machep (floating point precision)
negep int Exponent of the smallest power of ibeta that, substracted from 1.0, gives something different
from 1.0.
epsneg float Floating-point number beta**negep.
iexp int Number of bits in the exponent (including its sign and bias).
minexp int Smallest (most negative) power of ibeta consistent with there being no leading zeros in the
mantissa.
xmin float Floating point number beta**minexp (the smallest [in magnitude] usable floating value).
maxexp int Smallest (positive) power of ibeta that causes overflow.
xmax float (1-epsneg) * beta**maxexp (the largest [in magnitude] usable floating value).
irnd int In range(6), information on what kind of rounding is done in addition, and on how
underflow is handled.
ngrd int Number of guard digits used when truncating the product of two mantissas to fit the
representation.
epsilon float Same as eps.
tiny float Same as xmin.
huge float Same as xmax.
preci- float - int(-log10(eps))
sion
resolu- float - 10**(-precision)
tion
Examples
>>> np.issctype(np.int32)
True
>>> np.issctype(list)
False
>>> np.issctype(1.1)
False
issubdtype(arg1, arg2)
Returns True if first argument is a typecode lower/equal in type hierarchy.
Parameters
arg1, arg2 : dtype_like
dtype or string representing a typecode.
Returns
out : bool
See Also:
issubsctype, issubclass_
numpy.core.numerictypes
Overview of numpy type hierarchy.
Examples
issubsctype(arg1, arg2)
Determine if the first argument is a subclass of the second argument.
Parameters
arg1, arg2 : dtype or dtype specifier
Data-types.
Returns
out : bool
The result.
See Also:
issctype, issubdtype, obj2sctype
Examples
issubclass_(arg1, arg2)
find_common_type(array_types, scalar_types)
Determine common type following standard coercion rules.
Parameters
array_types : sequence
A list of dtypes or dtype convertible objects representing arrays.
scalar_types : sequence
A list of dtypes or dtype convertible objects representing scalars.
Returns
datatype : dtype
The common data type, which is the maximum of array_types ignoring scalar_types,
unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is
not understood, then None is returned.
See Also:
dtype, common_type, can_cast, mintypecode
Examples
The standard casting rules ensure that a scalar cannot up-cast an array unless the scalar is of a fundamentally
different kind of data (i.e. under a different hierarchy in the data type hierarchy) then the array:
Type specifier strings are convertible to dtypes and can therefore be used instead of dtypes:
3.4.4 Miscellaneous
Examples
sctype2char(sctype)
Return the string representation of a scalar dtype.
Parameters
sctype : scalar dtype or object
If a scalar dtype, the corresponding string character is returned. If an object, sctype2char
tries to infer its scalar type and then return the corresponding string character.
Returns
typechar : str
The string character corresponding to the scalar type.
Raises
ValueError :
If sctype is an object for which the type can not be inferred.
See Also:
Examples
Examples
Notes
If the file contains pickle data, then whatever is stored in the pickle is returned.
If the file is a .npy file, then an array is returned.
If the file is a .npz file, then a dictionary-like object is returned, containing {filename: array}
key-value pairs, one for each file in the archive.
Examples
Store data to disk, and load it again:
Mem-map the stored array, and then access the second row directly from disk:
save(file, arr)
Save an array to a binary file in NumPy .npy format.
Parameters
file : file or str
File or filename to which the data is saved. If file is a file-object, then the filename is
unchanged. If file is a string, a .npy extension will be appended to the file name if it
does not already have one.
arr : array_like
Array data to be saved.
See Also:
savez
Save several arrays into a .npz compressed archive
savetxt, load
Notes
For a description of the .npy format, see format.
Examples
>>> x = np.arange(10)
>>> np.save(outfile, x)
>>> outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> np.load(outfile)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Arrays to save to the file. Since it is not possible for Python to know the names of the
arrays outside savez, the arrays will be saved with names arr_0, arr_1, and so on.
These arguments can be any expression.
**kwds : Keyword arguments, optional
Arrays to save to the file. Arrays will be saved in the file with the keyword names.
Returns
None :
See Also:
save
Save a single array to a binary file in NumPy format.
savetxt
Save an array to a file as plain text.
Notes
The .npz file format is a zipped archive of files named after the variables they contain. Each file contains one
variable in .npy format. For a description of the .npy format, see format.
When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object which
can be queried for its list of arrays (with the .files attribute), and for the arrays themselves.
Examples
Using savez with *args, the arrays are saved with default names.
>>> np.savez(outfile, x, y)
>>> outfile.seek(0) # Only needed here to simulate closing & reopening file
>>> npzfile = np.load(outfile)
>>> npzfile.files
[arr_1, arr_0]
>>> npzfile[arr_0]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Using savez with **kwds, the arrays are saved with the keyword names.
Returns
out : ndarray
Data read from the text file.
See Also:
load, fromstring, fromregex
genfromtxt
Load data with missing values handled as specified.
scipy.io.loadmat
reads Matlab(R) data files
Notes
This function aims to be a fast reader for simply formatted files. The genfromtxt function provides more sophis-
ticated handling of, e.g., lines with missing values.
Examples
>>> from StringIO import StringIO # StringIO behaves like a file object
>>> c = StringIO("0 1\n2 3")
>>> np.loadtxt(c)
array([[ 0., 1.],
[ 2., 3.]])
>>> c = StringIO("1,0,2\n3,0,4")
>>> x, y = np.loadtxt(c, delimiter=,, usecols=(0, 2), unpack=True)
>>> x
array([ 1., 3.])
>>> y
array([ 2., 4.])
save
Save an array to a binary file in NumPy .npy format
savez
Save several arrays into a .npz compressed archive
Notes
Further explanation of the fmt parameter (%[flag]width[.precision]specifier):
flags:
- : left justify
+ : Forces to preceed result with + or -.
0 : Left pad the number with zeros instead of space (see width).
width:
Minimum number of characters to be printed. The value is not truncated if it has more characters.
precision:
References
[R268]
Examples
>>> x = y = z = np.arange(0.0,5.0,1.0)
>>> np.savetxt(test.out, x, delimiter=,) # X is an array
>>> np.savetxt(test.out, (x,y,z)) # x,y,z equal sized 1D arrays
>>> np.savetxt(test.out, x, fmt=%1.4e) # use exponential notation
numpy.loadtxt
equivalent function when no data is missing.
Notes
When spaces are used as delimiters, or when no delimiter has been given as input, there should not be any
missing data between two fields.
When the variables are named (either by a flexible dtype or with names, there must not be any header in
the file (else a ValueError exception is raised).
Individual values are not stripped of spaces by default. When using a custom converter, make sure the
function does remove spaces.
Examples
>>> s = StringIO("1,1.3,abcde")
>>> data = np.genfromtxt(s, dtype=[(myint,i8),(myfloat,f8),
... (mystring,S5)], delimiter=",")
>>> data
array((1, 1.3, abcde),
dtype=[(myint, <i8), (myfloat, <f8), (mystring, |S5)])
>>> s.seek(0)
>>> data = np.genfromtxt(s, dtype="i8,f8,S5",
... names=[myint,myfloat,mystring], delimiter=",")
>>> data
array((1, 1.3, abcde),
dtype=[(myint, <i8), (myfloat, <f8), (mystring, |S5)])
>>> s = StringIO("11.3abcde")
>>> data = np.genfromtxt(s, dtype=None, names=[intvar,fltvar,strvar],
... delimiter=[1,3,5])
>>> data
array((1, 1.3, abcde),
dtype=[(intvar, <i8), (fltvar, <f8), (strvar, |S5)])
Regular expression used to parse the file. Groups in the regular expression correspond
to fields in the dtype.
dtype : dtype or list of dtypes
Dtype for the structured array.
Returns
output : ndarray
The output array, containing the part of the content of file that was matched by regexp.
output is always a structured array.
Raises
TypeError :
When dtype is not a valid dtype for a structured array.
See Also:
fromstring, loadtxt
Notes
Dtypes for structured arrays can be specified in several forms, but all forms specify at least the data type and
field name. For details see doc.structured_arrays.
Examples
>>> f = open(test.dat, w)
>>> f.write("1312 foo\n1534 bar\n444 qux")
>>> f.close()
If provided and not empty, then the data will be interpreted as ASCII text with decimal
numbers. This argument is interpreted as the string separating numbers in the data.
Extra whitespace between elements is also ignored.
Returns
arr : array
The constructed array.
Raises
ValueError :
If the string is not the correct size to satisfy the requested dtype and count.
Examples
Invalid inputs:
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision is lost,
so this method is not a good choice for files intended to archive data or transport data between machines with
different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense
of speed and file size.
tolist()
Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible
Python type.
Parameters
none :
Returns
y : list
The possibly nested list of array elements.
Notes
The array may be recreated, a = np.array(a.tolist()).
Examples
Returns
string : str
The string representation of an array.
See Also:
array_str, array2string, set_printoptions
Examples
>>> np.array_repr(np.array([1,2]))
array([1, 2])
>>> np.array_repr(np.ma.array([0.]))
MaskedArray([ 0.])
>>> np.array_repr(np.array([], np.int32))
array([], dtype=int32)
Examples
>>> np.array_str(np.arange(3))
[0 1 2]
class memmap()
Create a memory-map to an array stored in a binary file on disk.
Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire
file into memory. Numpys memmaps are array-like objects. This differs from Pythons mmap module, which
uses file-like objects.
Parameters
filename : str or file-like object
The file name or file object to be used as the array data buffer.
dtype : data-type, optional
The data-type used to interpret the file contents. Default is uint8.
mode : {r+, r, w+, c}, optional
The file is opened in this mode:
r Open existing file for reading only.
r+ Open existing file for reading and writing.
w+ Create or overwrite existing file for reading and writing.
c Copy-on-write: assignments affect data in memory, but changes are not saved to disk. The file on disk is
read-only.
Default is r+.
offset : int, optional
In the file, array data starts at this offset. Since offset is measured in bytes, it should be
a multiple of the byte-size of dtype. Requires shape=None. The default is 0.
shape : tuple, optional
The desired shape of the array. By default, the returned array will be 1-D with the
number of elements determined by file size and data-type.
order : {C, F}, optional
Specify the order of the ndarray memory layout: C (row-major) or Fortran (column-
major). This only has an effect if the shape is greater than 1-D. The default order is
C.
Notes
The memmap object can be used anywhere an ndarray is accepted. Given a memmap fp, isinstance(fp,
numpy.ndarray) returns True.
Memory-mapped arrays use the Python memory-map object which (prior to Python 2.5) does not allow files to
be larger than a certain size depending on the platform. This size is always < 2GB even on 64-bit systems.
Examples
This example uses a temporary file so that doctest doesnt write files to your directory. You would use a normal
filename.
Create a memmap with dtype and shape that matches our data:
>>> del fp
Read-only memmap:
Copy-on-write memmap:
Its possible to assign to copy-on-write array, but values are only written into the memory copy of the array, and
not written to disk:
>>> fpc
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> fpc[0,:] = 0
>>> fpc
memmap([[ 0., 0., 0., 0.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
>>> fpr
memmap([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32)
Attributes
filename str Path to the mapped file.
offset int Offset position in the file.
mode str File mode.
Methods
close() Close the memmap file.
flush() Write any changes in the array to the file on disk.
close()
Close the memmap file. Does nothing.
flush()
Write any changes in the array to the file on disk.
For further information, see memmap.
Parameters
None :
See Also:
memmap
Examples
Floating point precision can be set:
>>> np.set_printoptions(precision=4)
>>> print np.array([1.123456789])
[ 1.1235]
>>> np.set_printoptions(threshold=5)
>>> print np.arange(10)
[0 1 2 ..., 7 8 9]
>>> np.set_printoptions(edgeitems=3,infstr=Inf,
... linewidth=75, nanstr=NaN, precision=8,
... suppress=False, threshold=1000)
get_printoptions()
Return the current print options.
Returns
print_opts : dict
Dictionary of current print options with keys
precision : int
threshold : int
edgeitems : int
linewidth : int
suppress : bool
nanstr : str
infstr : str
For a full description of these options, see set_printoptions.
See Also:
set_printoptions, set_string_function
set_string_function(f, repr=1)
Set a Python function to be used when pretty printing arrays.
Parameters
f : function or None
Function to be used to pretty print arrays. The function should expect a single array
argument and return a string of the representation of the array. If None, the function is
reset to the default NumPy function to print arrays.
repr : bool, optional
If True (default), the function for pretty printing (__repr__) is set, if False the func-
tion that returns the default string representation (__str__) is set.
See Also:
set_printoptions, get_printoptions
Examples
>>> np.set_string_function(None)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], l)
repr affects either pretty printing or normal string representation. Note that __repr__ is still affected by
setting __str__ because the width of each array element in the returned string becomes equal to the length of
the result of __str__().
>>> x = np.arange(4)
>>> np.set_string_function(lambda x:random, repr=False)
>>> x.__str__()
random
>>> x.__repr__()
array([ 0, 1, 2, 3])
binary_repr(num[, width]) Return the binary representation of the input number as a string.
base_repr(number[, base, padding]) Return a string representation of a number in the given base system.
binary_repr(num, width=None)
Return the binary representation of the input number as a string.
For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the twos
complement of the number is returned, with respect to that width.
In a twos-complement system negative numbers are represented by the twos complement of the absolute
value. This is the most common method of representing signed integers on computers [R23]. A N-bit twos-
complement system can represent every integer in the range 2N 1 to +2N 1 1.
Parameters
num : int
Only an integer decimal number can be used.
width : int, optional
The length of the returned string if num is positive, the length of the twos complement
if num is negative.
Returns
bin : str
Binary representation of num or twos complement of num.
See Also:
base_repr
Return a string representation of a number in the given base system.
Notes
binary_repr is equivalent to using base_repr with base 2, but about 25x faster.
References
[R23]
Examples
>>> np.binary_repr(3)
11
>>> np.binary_repr(-3)
-11
>>> np.binary_repr(3, width=4)
0011
The twos complement is returned when the input number is negative and width is specified:
binary_repr
Faster version of base_repr for base 2 that also handles negative numbers.
Examples
>>> np.base_repr(5)
101
>>> np.base_repr(6, 5)
11
>>> np.base_repr(7, base=5, padding=3)
00012
Path to the directory where the source file gets downloaded to for use. If destpath is
None, a temporary directory will be created. The default path is the current directory.
Notes
URLs require a scheme string (http://) to be used, without it they will fail:
Examples
>>> ds = DataSource(/home/guido)
>>> urlname = http://www.google.com/index.html
>>> gfile = ds.open(http://www.google.com/index.html) # remote file
>>> ds.abspath(urlname)
/home/guido/www.google.com/site/index.html
Methods
abspath(path) Return absolute path of file in the DataSource directory.
exists(path) Test if path exists.
open(path[, mode]) Open and return file-like object.
abspath(path)
Return absolute path of file in the DataSource directory.
If path is an URL, then abspath will return either the location the file exists locally or the location it would
exist when opened using the open method.
Parameters
path : str
Can be a local file or a remote URL.
Returns
out : str
Complete path, including the DataSource destination directory.
Notes
The functionality is based on os.path.abspath.
exists(path)
Test if path exists.
Test if path exists as (and in this order):
a local file.
a remote URL that has been downloaded and stored locally in the DataSource directory.
a remote URL that has not been downloaded, but is valid and accessible.
Parameters
path : str
Can be a local file or a remote URL.
Returns
out : bool
True if path exists.
Notes
When path is an URL, exists will return True if its either stored locally in the DataSource directory, or is
a valid remote URL. DataSource does not discriminate between the two, the file is accessible if it exists in
either location.
open(path, mode=r)
Open and return file-like object.
If path is an URL, it will be downloaded, stored in the DataSource directory and opened from there.
Parameters
path : str
Local file path or URL to open.
mode : {r, w, a}, optional
Mode to open path. Mode r for reading, w for writing, a to append. Available
modes depend on the type of object specified by path. Default is r.
Returns
out : file object
File object.
numpy.fft
for definition of the DFT and conventions used.
ifft
The inverse of fft.
fft2
The two-dimensional FFT.
fftn
The n-dimensional FFT.
rfftn
The n-dimensional FFT of real input.
fftfreq
Frequency bins for given FFT parameters.
Notes
FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform (DFT) can be calculated efficiently,
by using symmetries in the calculated terms. The symmetry is highest when n is a power of 2, and the transform
is therefore most efficient for these sizes.
The DFT is defined, with the conventions used in this implementation, in the documentation for the numpy.fft
module.
References
[CT]
Examples
9.95839695e-17 +2.33482938e-16j,
0.00000000e+00 +1.66837030e-15j,
1.14383329e-17 +1.22460635e-16j,
-1.64863782e-15 +1.77635684e-15j])
In this example, real input has an FFT which is Hermitian, i.e., symmetric in the real part and anti-symmetric in
the imaginary part, as described in the numpy.fft documentation.
80
60
40
20
0
20
40
60
80
100
0.6 0.4 0.2 0.0 0.2 0.4 0.6
numpy.fft
An introduction, with definitions and general explanations.
fft
The one-dimensional (forward) FFT, of which ifft is the inverse
ifft2
The two-dimensional inverse FFT.
ifftn
The n-dimensional inverse FFT.
Notes
If the input parameter n is larger than the size of the input, the input is padded by appending zeros at the end.
Even though this is the common approach, it might lead to surprising results. If a different padding is desired, it
must be performed before calling ifft.
Examples
0.03
real
0.02 imaginary
0.01
0.00
0.01
0.02
0.03
0 50 100 150 200 250 300 350 400
numpy.fft
Overall view of discrete Fourier transforms, with definitions and conventions used.
ifft2
The inverse two-dimensional FFT.
fft
The one-dimensional FFT.
fftn
The n-dimensional FFT.
fftshift
Shifts zero-frequency terms to the center of the array. For two-dimensional input, swaps first and third
quadrants, and second and fourth quadrants.
Notes
fft2 is just fftn with a different default for axes.
The output, analogously to fft, contains the term for zero frequency in the low-order corner of the transformed
axes, the positive frequency terms in the first half of these axes, the term for the Nyquist frequency in the middle
of the axes and the negative frequency terms in the second half of the axes, in order of decreasingly negative
frequency.
See fftn for details and a plotting example, and numpy.fft for definitions and conventions used.
Examples
if s is not given, the shape of the input (along the axes specified by axes) is used. See
notes for issue on ifft zero padding.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last two axes are used. A repeated
index in axes means the transform over that axis is performed multiple times. A one-
element sequence means that a one-dimensional FFT is performed.
Returns
out : complex ndarray
The truncated or zero-padded input, transformed along the axes indicated by axes, or
the last two axes if axes is not given.
Raises
ValueError :
If s and axes have different length, or axes not given and len(s) != 2.
IndexError :
If an element of axes is larger than than the number of axes of a.
See Also:
numpy.fft
Overall view of discrete Fourier transforms, with definitions and conventions used.
fft2
The forward 2-dimensional FFT, of which ifft2 is the inverse.
ifftn
The inverse of the n-dimensional FFT.
fft
The one-dimensional FFT.
ifft
The one-dimensional inverse FFT.
Notes
ifft2 is just ifftn with a different default for axes.
See ifftn for details and a plotting example, and numpy.fft for definition and conventions used.
Zero-padding, analogously with ifft, is performed by appending zeros to the input along the specified dimension.
Although this is the common approach, it might lead to surprising results. If another form of zero padding is
desired, it must be performed before ifft2 is called.
Examples
>>> a = 4 * np.eye(4)
>>> np.fft.ifft2(a)
array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
[ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
[ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-
dimensional array by means of the Fast Fourier Transform (FFT).
Parameters
a : array_like
Input array, can be complex.
s : sequence of ints, optional
Shape (length of each transformed axis) of the output (s[0] refers to axis 0, s[1] to axis
1, etc.). This corresponds to n for fft(x, n). Along any axis, if the given shape is smaller
than that of the input, the input is cropped. If it is larger, the input is padded with zeros.
if s is not given, the shape of the input (along the axes specified by axes) is used.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last len(s) axes are used, or
all axes if s is also not specified. Repeated indices in axes means that the transform over
that axis is performed multiple times.
Returns
out : complex ndarray
The truncated or zero-padded input, transformed along the axes indicated by axes, or
by a combination of s and a, as explained in the parameters section above.
Raises
ValueError :
If s and axes have different length.
IndexError :
If an element of axes is larger than than the number of axes of a.
See Also:
numpy.fft
Overall view of discrete Fourier transforms, with definitions and conventions used.
ifftn
The inverse of fftn, the inverse n-dimensional FFT.
fft
The one-dimensional FFT, with definitions and conventions used.
rfftn
The n-dimensional FFT of real input.
fft2
The two-dimensional FFT.
fftshift
Shifts zero-frequency terms to centre of array
Notes
The output, analogously to fft, contains the term for zero frequency in the low-order corner of all axes, the
positive frequency terms in the first half of all axes, the term for the Nyquist frequency in the middle of all axes
and the negative frequency terms in the second half of all axes, in order of decreasingly negative frequency.
See numpy.fft for details, definitions and conventions used.
Examples
50
100
150
0 50 100 150
numpy.fft
Overall view of discrete Fourier transforms, with definitions and conventions used.
fftn
The forward n-dimensional FFT, of which ifftn is the inverse.
ifft
The one-dimensional inverse FFT.
ifft2
The two-dimensional inverse FFT.
ifftshift
Undoes fftshift, shifts zero-frequency terms to beginning of array.
Notes
See numpy.fft for definitions and conventions used.
Zero-padding, analogously with ifft, is performed by appending zeros to the input along the specified dimension.
Although this is the common approach, it might lead to surprising results. If another form of zero padding is
desired, it must be performed before ifftn is called.
Examples
>>> a = np.eye(4)
>>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))
array([[ 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
[ 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
50
100
150
0 50 100 150
rfft(a[, n, axis]) Compute the one-dimensional discrete Fourier Transform for real input.
irfft(a[, n, axis]) Compute the inverse of the n-point DFT for real input.
rfft2(a[, s, axes]) Compute the 2-dimensional FFT of a real array.
irfft2(a[, s, axes]) Compute the 2-dimensional inverse FFT of a real array.
rfftn(a[, s, axes]) Compute the N-dimensional discrete Fourier Transform for real input.
irfftn(a[, s, axes]) Compute the inverse of the N-dimensional FFT of real input.
rfft(a, n=None, axis=-1)
Compute the one-dimensional discrete Fourier Transform for real input.
This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by
means of an efficient algorithm called the Fast Fourier Transform (FFT).
Parameters
a : array_like
Input array
n : int, optional
Number of points along transformation axis in the input to use. If n is smaller than the
length of the input, the input is cropped. If it is larger, the input is padded with zeros. If
n is not given, the length of the input (along the axis specified by axis) is used.
axis : int, optional
Axis over which to compute the FFT. If not given, the last axis is used.
Returns
out : complex ndarray
The truncated or zero-padded input, transformed along the axis indicated by axis, or the
last one if axis is not specified. The length of the transformed axis is n/2+1.
Raises
IndexError :
If axis is larger than the last axis of a.
See Also:
numpy.fft
For definition of the DFT and conventions used.
irfft
The inverse of rfft.
fft
The one-dimensional FFT of general (complex) input.
fftn
The n-dimensional FFT.
rfftn
The n-dimensional FFT of real input.
Notes
When the DFT is computed for purely real input, the output is Hermite-symmetric, i.e. the negative frequency
terms are just the complex conjugates of the corresponding positive-frequency terms, and the negative-frequency
terms are therefore redundant. This function does not compute the negative frequency terms, and the length of
the transformed axis of the output is therefore n/2+1.
When A = rfft(a), A[0] contains the zero-frequency term, which must be purely real due to the Hermite
symmetry.
If n is even, A[-1] contains the term for frequencies n/2 and -n/2, and must also be purely real. If n is odd,
A[-1] contains the term for frequency A[(n-1)/2], and is complex in the general case.
If the input a contains an imaginary part, it is silently discarded.
Examples
Notice how the final element of the fft output is the complex conjugate of the second element, for real input. For
rfft, this symmetry is exploited to compute only the non-negative frequency terms.
irfft(a, n=None, axis=-1)
Compute the inverse of the n-point DFT for real input.
This function computes the inverse of the one-dimensional n-point discrete Fourier Transform of real input
computed by rfft. In other words, irfft(rfft(a), len(a)) == a to within numerical accuracy. (See
Notes below for why len(a) is necessary here.)
The input is expected to be in the form returned by rfft, i.e. the real zero-frequency term followed by the complex
positive frequency terms in order of increasing frequency. Since the discrete Fourier Transform of real input is
Hermite-symmetric, the negative frequency terms are taken to be the complex conjugates of the corresponding
positive frequency terms.
Parameters
a : array_like
The input array.
n : int, optional
Length of the transformed axis of the output. For n output points, n/2+1 input points
are necessary. If the input is longer than this, it is cropped. If it is shorter than this, it is
padded with zeros. If n is not given, it is determined from the length of the input (along
the axis specified by axis).
axis : int, optional
Axis over which to compute the inverse FFT.
Returns
out : ndarray
The truncated or zero-padded input, transformed along the axis indicated by axis, or the
last one if axis is not specified. The length of the transformed axis is n, or, if n is not
given, 2*(m-1) where m is the length of the transformed axis of the input. To get an
odd number of output points, n must be specified.
Raises
IndexError :
If axis is larger than the last axis of a.
See Also:
numpy.fft
For definition of the DFT and conventions used.
rfft
The one-dimensional FFT of real input, of which irfft is inverse.
fft
The one-dimensional FFT.
irfft2
The inverse of the two-dimensional FFT of real input.
irfftn
The inverse of the n-dimensional FFT of real input.
Notes
Returns the real valued n-point inverse discrete Fourier transform of a, where a contains the non-negative fre-
quency terms of a Hermite-symmetric sequence. n is the length of the result, not the input.
If you specify an n such that a must be zero-padded or truncated, the extra/removed values will be
added/removed at high frequencies. One can thus resample a series to m points via Fourier interpolation by:
a_resamp = irfft(rfft(a), m).
Examples
Notice how the last term in the input to the ordinary ifft is the complex conjugate of the second term, and the
output has zero imaginary part everywhere. When calling irfft, the negative frequencies are not specified, and
the output array is purely real.
rfft2(a, s=None, axes=(-2, -1))
Compute the 2-dimensional FFT of a real array.
Parameters
a : array
Input array, taken to be real.
s : sequence of ints, optional
Shape of the FFT.
axes : sequence of ints, optional
Axes over which to compute the FFT.
Returns
out : ndarray
The result of the real 2-D FFT.
See Also:
rfftn
Compute the N-dimensional discrete Fourier Transform for real input.
Notes
This is really just rfftn with different default behavior. For more details see rfftn.
irfft2(a, s=None, axes=(-2, -1))
Compute the 2-dimensional inverse FFT of a real array.
Parameters
a : array_like
The input array
s : sequence of ints, optional
Shape of the inverse FFT.
axes : sequence of ints, optional
The axes over which to compute the inverse fft. Default is the last two axes.
Returns
out : ndarray
The result of the inverse real 2-D FFT.
See Also:
irfftn
Compute the inverse of the N-dimensional FFT of real input.
Notes
This is really irfftn with different defaults. For more details see irfftn.
rfftn(a, s=None, axes=None)
Compute the N-dimensional discrete Fourier Transform for real input.
This function computes the N-dimensional discrete Fourier Transform over any number of axes in an M-
dimensional real array by means of the Fast Fourier Transform (FFT). By default, all axes are transformed,
with the real transform performed over the last axis, while the remaining transforms are complex.
Parameters
a : array_like
Input array, taken to be real.
s : sequence of ints, optional
Shape (length along each transformed axis) to use from the input. (s[0] refers to axis
0, s[1] to axis 1, etc.). The final element of s corresponds to n for rfft(x, n),
while for the remaining axes, it corresponds to n for fft(x, n). Along any axis, if
the given shape is smaller than that of the input, the input is cropped. If it is larger,
the input is padded with zeros. if s is not given, the shape of the input (along the axes
specified by axes) is used.
axes : sequence of ints, optional
Axes over which to compute the FFT. If not given, the last len(s) axes are used, or
all axes if s is also not specified.
Returns
out : complex ndarray
The truncated or zero-padded input, transformed along the axes indicated by axes, or by
a combination of s and a, as explained in the parameters section above. The length of
the last axis transformed will be s[-1]//2+1, while the remaining transformed axes
will have lengths according to s, or unchanged from the input.
Raises
ValueError :
If s and axes have different length.
IndexError :
If an element of axes is larger than than the number of axes of a.
See Also:
irfftn
The inverse of rfftn, i.e. the inverse of the n-dimensional FFT of real input.
fft
The one-dimensional FFT, with definitions and conventions used.
rfft
The one-dimensional FFT of real input.
fftn
The n-dimensional FFT.
rfft2
The two-dimensional FFT of real input.
Notes
The transform for real input is performed over the last transformation axis, as by rfft, then the transform over
the remaining axes is performed as by fftn. The order of the output is as for rfft for the final transformation axis,
and as for fftn for the remaining transformation axes.
See fft for details, definitions and conventions used.
Examples
rfftn
The forward n-dimensional FFT of real input, of which ifftn is the inverse.
fft
The one-dimensional FFT, with definitions and conventions used.
irfft
The inverse of the one-dimensional FFT of real input.
irfft2
The inverse of the two-dimensional FFT of real input.
Notes
See fft for definitions and conventions used.
See rfft for definitions and conventions used for real input.
Examples
hfft(a[, n, axis]) Compute the FFT of a signal whose spectrum has Hermitian symmetry.
ihfft(a[, n, axis]) Compute the inverse FFT of a signal whose spectrum has Hermitian symmetry.
hfft(a, n=None, axis=-1)
Compute the FFT of a signal whose spectrum has Hermitian symmetry.
Parameters
a : array_like
The input array.
n : int, optional
The length of the FFT.
axis : int, optional
The axis over which to compute the FFT, assuming Hermitian symmetry of the spec-
trum. Default is the last axis.
Returns
out : ndarray
The transformed input.
See Also:
rfft
Compute the one-dimensional FFT for real input.
ihfft
The inverse of hfft.
Notes
hfft/ihfft are a pair analogous to rfft/irfft, but for the opposite case: here the signal is real in the frequency domain
and has Hermite symmetry in the time domain. So here its hfft for which you must supply the length of the
result if it is to be odd: ihfft(hfft(a), len(a)) == a, within numerical accuracy.
Examples
Notes
hfft/ihfft are a pair analogous to rfft/irfft, but for the opposite case: here the signal is real in the frequency domain
and has Hermite symmetry in the time domain. So here its hfft for which you must supply the length of the
result if it is to be odd: ihfft(hfft(a), len(a)) == a, within numerical accuracy.
Parameters
n : int
Window length.
d : scalar
Sample spacing.
Returns
out : ndarray
The array of length n, containing the sample frequencies.
Examples
fftshift(x, axes=None)
Shift the zero-frequency component to the center of the spectrum.
This function swaps half-spaces for all axes listed (defaults to all). Note that y[0] is the Nyquist component
only if len(x) is even.
Parameters
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to shift. Default is None, which shifts all axes.
Returns
y : ndarray
The shifted array.
See Also:
ifftshift
The inverse of fftshift.
Examples
ifftshift(x, axes=None)
The inverse of fftshift.
Parameters
x : array_like
Input array.
axes : int or shape tuple, optional
Axes over which to calculate. Defaults to None, which shifts all axes.
Returns
y : ndarray
The shifted array.
See Also:
fftshift
Shift zero-frequency component to the center of the spectrum.
Examples
Fourier analysis is fundamentally a method for expressing a function as a sum of periodic components, and for recover-
ing the signal from those components. When both the function and its Fourier transform are replaced with discretized
counterparts, it is called the discrete Fourier transform (DFT). The DFT has become a mainstay of numerical com-
puting in part because of a very fast algorithm for computing it, called the Fast Fourier Transform (FFT), which was
known to Gauss (1805) and was brought to light in its current form by Cooley and Tukey [CT]. Press et al. [NR]
provide an accessible introduction to Fourier analysis and its applications.
Because the discrete Fourier transform separates its input into components that contribute at discrete frequencies, it
has a great number of applications in digital signal processing, e.g., for filtering, and in this context the discretized
input to the transform is customarily referred to as a signal, which exists in the time domain. The output is called a
spectrum or transform and exists in the frequency domain.
There are many ways to define the DFT, varying in the sign of the exponent, normalization, etc. In this implementation,
the DFT is defined as
n1
X mk
Ak = am exp 2i k = 0, . . . , n 1.
m=0
n
The DFT is in general defined for complex inputs and outputs, and a single-frequency component at linear frequency
f is represented by a complex exponential am = exp{2i f mt}, where t is the sampling interval.
The values in the result follow so-called standard order: If A = fft(a, n), then A[0] contains the zero-
frequency term (the mean of the signal), which is always purely real for real inputs. Then A[1:n/2] contains
the positive-frequency terms, and A[n/2+1:] contains the negative-frequency terms, in order of decreasingly nega-
tive frequency. For an even number of input points, A[n/2] represents both positive and negative Nyquist frequency,
and is also purely real for real input. For an odd number of input points, A[(n-1)/2] contains the largest positive
frequency, while A[(n+1)/2] contains the largest negative frequency. The routine np.fft.fftfreq(A) returns
an array giving the frequencies of corresponding elements in the output. The routine np.fft.fftshift(A) shifts
transforms and their frequencies to put the zero-frequency components in the middle, and np.fft.ifftshift(A)
undoes that shift.
When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and
np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).
It differs from the forward transform by the sign of the exponential argument and the normalization by 1/n.
When the input is purely real, its transform is Hermitian, i.e., the component at frequency fk is the complex conjugate
of the component at frequency fk , which means that for real inputs there is no information in the negative frequency
components that is not already available from the positive frequency components. The family of rfft functions is
designed to operate on real inputs, and exploits this symmetry by computing only the positive frequency components,
up to and including the Nyquist frequency. Thus, n input points produce n/2+1 complex output points. The inverses
of this family assumes the same symmetry of its input, and for an output of n points uses n/2+1 input points.
Correspondingly, when the spectrum is purely real, the signal is Hermitian. The hfft family of functions exploits this
symmetry by using n/2+1 complex points in the input (time) domain for n real points in the frequency domain.
In higher dimensions, FFTs are used, e.g., for image analysis and filtering. The computational efficiency of the FFT
means that it can also be a faster way to compute large convolutions, using the property that a convolution in the time
domain is equivalent to a point-by-point multiplication in the frequency domain.
In two dimensions, the DFT is defined as
M 1 N 1
X X mk nl
Akl = amn exp 2i + k = 0, . . . , N 1; l = 0, . . . , M 1,
m=0 n=0
M N
which extends in the obvious way to higher dimensions, and the inverses in higher dimensions also extend in the same
way.
References
Examples
dot(a, b)
Dot product of two arrays.
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without
complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:
Parameters
a : array_like
First argument.
b : array_like
Second argument.
Returns
output : ndarray
Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a
scalar is returned; otherwise an array is returned.
Raises
ValueError :
If the last dimension of a is not the same size as the second-to-last dimension of b.
See Also:
vdot
Complex-conjugating dot product.
tensordot
Sum products over arbitrary axes.
Examples
>>> np.dot(3, 4)
12
>>> a = np.arange(3*4*5*6).reshape((3,4,5,6))
>>> b = np.arange(3*4*5*6)[::-1].reshape((5,4,6,3))
>>> np.dot(a, b)[2,3,2,1,2,2]
499128
vdot(a, b)
Return the dot product of two vectors.
The vdot(a, b) function handles complex numbers differently than dot(a, b). If the first argument is complex the
complex conjugate of the first argument is used for the calculation of the dot product.
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (with
complex conjugation of a). For N dimensions it is a sum product over the last axis of a and the second-to-last
of b:
Parameters
a : array_like
If a is complex the complex conjugate is taken before calculation of the dot product.
b : array_like
Second argument to the dot product.
Returns
output : ndarray
Returns dot product of a and b. Can be an int, float, or complex depending on the types
of a and b.
See Also:
dot
Return the dot product without using the complex conjugate of the first argument.
Notes
The dot product is the summation of element wise multiplication.
n
X
ab= ai bi = a1 b1 + a2 b2 + + an bn
i=1
Examples
>>> a = np.array([1+2j,3+4j])
>>> b = np.array([5+6j,7+8j])
>>> np.vdot(a, b)
(70-8j)
>>> np.vdot(b, a)
(70+8j)
>>> a = np.array([[1, 4], [5, 6]])
>>> b = np.array([[4, 1], [2, 2]])
>>> np.vdot(a, b)
30
>>> np.vdot(b, a)
30
inner(a, b)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum
product over the last axes.
Parameters
a, b : array_like
If a and b are nonscalar, their last dimensions of must match.
Returns
out : ndarray
out.shape = a.shape[:-1] + b.shape[:-1]
Raises
ValueError :
If the last dimension of a and b has different size.
See Also:
tensordot
Sum products over arbitrary axes.
dot
Generalised matrix product, using second last dimension of b.
Notes
For vectors (1-D arrays) it computes the ordinary inner-product:
np.inner(a, b) = sum(a[:]*b[:])
or explicitly:
np.inner(a, b)[i0,...,ir-1,j0,...,js-1]
= sum(a[i0,...,ir-1,:]*b[j0,...,js-1,:])
np.inner(a,b) = a*b
Examples
Ordinary inner product for vectors:
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
A multidimensional example:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])
outer(a, b)
Compute the outer product of two vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [R63]
is:
Parameters
a, b : array_like, shape (M,), (N,)
First and second input vectors. Inputs are flattened if they are not already 1-dimensional.
Returns
out : ndarray, shape (M, N)
out[i, j] = a[i] * b[j]
References
[R63]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:
tensordot(a, b, axes=2)
Compute tensor dot product along specified axes for arrays >= 1-D.
Given two tensors (arrays of dimension greater than or equal to one), a and b, and an array_like object containing
two array_like objects, (a_axes, b_axes), sum the products of as and bs elements (components) over
the axes specified by a_axes and b_axes. The third argument can be a single non-negative integer_like
scalar, N; if it is such, then the last N dimensions of a and the first N dimensions of b are summed over.
Parameters
a, b : array_like, len(shape) >= 1
Tensors to dot.
axes : variable type
* integer_like scalar :
Number of axes to sum over (applies to both arrays); or
* array_like, shape = (2,), both elements array_like :
Axes to be summed over, first sequence applying to a, second to b.
See Also:
numpy.dot
Notes
When there is more than one axis to sum over - and they are not the last (first) axes of a (b) - the argument axes
should consist of two sequences of the same length, with the first axis to sum over given first in both sequences,
the second axis second, and so forth.
Examples
A traditional example:
>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> c = np.tensordot(a,b, axes=([1,0],[0,1]))
>>> c.shape
(5, 2)
>>> c
array([[ 4400., 4730.],
[ 4532., 4874.],
[ 4664., 5018.],
[ 4796., 5162.],
[ 4928., 5306.]])
>>> np.tensordot(a, A, 1)
array([[[acc, bdd],
[aaacccc, bbbdddd]],
[[aaaaacccccc, bbbbbdddddd],
[aaaaaaacccccccc, bbbbbbbdddddddd]]], dtype=object)
matrix_power(M, n)
Raise a square matrix to the (integer) power n.
For positive integers n, the power is computed by repeated matrix squarings and matrix multiplications. If n ==
0, the identity matrix of the same shape as M is returned. If n < 0, the inverse is computed and then raised to
the abs(n).
Parameters
M : ndarray or matrix object
Matrix to be powered. Must be square, i.e. M.shape == (m, m), with m a posi-
tive integer.
n : int
The exponent can be any integer or long integer, positive, negative, or zero.
Returns
M**n : ndarray or matrix object
The return value is the same shape and type as M; if the exponent is positive or zero
then the type of the elements is the same as those of M. If the exponent is negative the
elements are floating-point.
Raises
LinAlgError :
If the matrix is not numerically invertible.
See Also:
matrix
Provides an equivalent function as the exponentiation operator (**, not ^).
Examples
kron(a, b)
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the second array scaled by the first.
Parameters
a, b : array_like
Returns
out : ndarray
See Also:
outer
The outer product
Notes
The function assumes that the number of dimenensions of a and b are the same, if necessary prepending the
smallest with ones. If a.shape = (r0,r1,..,rN) and b.shape = (s0,s1,...,sN), the Kronecker product has shape
(r0*s0, r1*s1, ..., rN*SN). The elements are products of elements from a and b, organized explicitly by:
where:
kt = it * st + jt, t = 0,...,N
In the common 2-D case (N=1), the block structure can be visualized:
Examples
>>> a = np.arange(100).reshape((2,5,2,5))
>>> b = np.arange(24).reshape((2,3,4))
>>> c = np.kron(a,b)
>>> c.shape
(2, 10, 6, 20)
>>> I = (1,3,0,2)
>>> J = (0,2,1)
>>> J1 = (0,) + J # extend to ndim=4
>>> S1 = (1,) + b.shape
>>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
>>> c[K] == a[I]*b[J]
True
3.7.2 Decompositions
Notes
The Cholesky decomposition is often used as a fast way of solving
Ax = b
Ly = b,
L.Hx = y.
Examples
>>> A = np.array([[1,-2j],[2j,5]])
>>> A
array([[ 1.+0.j, 0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> L = np.linalg.cholesky(A)
>>> L
array([[ 1.+0.j, 0.+0.j],
[ 0.+2.j, 1.+0.j]])
>>> np.dot(L, L.T.conj()) # verify that L * L.H = A
array([[ 1.+0.j, 0.-2.j],
[ 0.+2.j, 5.+0.j]])
>>> A = [[1,-2j],[2j,5]] # what happens if A is only array_like?
>>> np.linalg.cholesky(A) # an ndarray object is returned
array([[ 1.+0.j, 0.+0.j],
[ 0.+2.j, 1.+0.j]])
>>> # But a matrix object is returned if A is a matrix object
>>> LA.cholesky(np.matrix(A))
matrix([[ 1.+0.j, 0.+0.j],
[ 0.+2.j, 1.+0.j]])
qr(a, mode=full)
Compute the qr factorization of a matrix.
Factor the matrix a as qr, where q is orthonormal and r is upper-triangular.
Parameters
a : array_like
Matrix to be factored, of shape (M, N).
mode : {full, r, economic}, optional
Specifies the values to be returned. full is the default. Economic mode is slightly
faster then r mode if only r is needed.
Returns
q : ndarray of float or complex, optional
The orthonormal matrix, of shape (M, K). Only returned if mode=full.
r : ndarray of float or complex, optional
The upper-triangular matrix, of shape (K, N) with K = min(M, N). Only returned when
mode=full or mode=r.
a2 : ndarray of float or complex, optional
Array of shape (M, N), only returned when mode=economic. The diagonal and
the upper triangle of a2 contains r, while the rest of the matrix is undefined.
Raises
LinAlgError :
If factoring fails.
Notes
This is an interface to the LAPACK routines dgeqrf, zgeqrf, dorgqr, and zungqr.
For more information on the qr factorization, see for example: http://en.wikipedia.org/wiki/QR_factorization
Subclasses of ndarray are preserved, so if a is of type matrix, all the return values will be matrices too.
Examples
>>> a = np.random.randn(9, 6)
>>> q, r = np.linalg.qr(a)
>>> np.allclose(a, np.dot(q, r)) # a does equal qr
True
>>> r2 = np.linalg.qr(a, mode=r)
>>> r3 = np.linalg.qr(a, mode=economic)
>>> np.allclose(r, r2) # mode=r returns the same r as mode=full
True
>>> # But only triu parts are guaranteed equal when mode=economic
>>> np.allclose(r, np.triu(r3[:6,:6], k=0))
True
If A = qr such that q is orthonormal (which is always possible via Gram-Schmidt), then x = inv(r) *
(q.T) * b. (In numpy practice, however, we simply use lstsq.)
Notes
The SVD is commonly written as a = U S V.H. The v returned by this function is V.H and u = U.
If U is a unitary matrix, it means that it satisfies U.H = inv(U).
The rows of v are the eigenvectors of a.H a. The columns of u are the eigenvectors of a a.H. For row i in v
and column i in u, the corresponding eigenvalue is s[i]**2.
If a is a matrix object (as opposed to an ndarray), then so are all the return values.
Examples
eigvalsh
eigenvalues of a symmetric or Hermitian (conjugate symmetric) array.
eigvals
eigenvalues of a non-symmetric array.
Notes
This is a simple interface to the LAPACK routines dgeev and zgeev which compute the eigenvalues and eigen-
vectors of, respectively, general real- and complex-valued square arrays.
The number w is an eigenvalue of a if there exists a vector v such that dot(a,v) = w * v. Thus, the arrays
a, w, and v satisfy the equations dot(a[i,:], v[i]) = w[i] * v[:,i] for i {0, ..., M 1}.
The array v of eigenvectors may not be of maximum rank, that is, some of the columns may be linearly depen-
dent, although round-off error may obscure that fact. If the eigenvalues are all different, then theoretically the
eigenvectors are linearly independent. Likewise, the (complex-valued) matrix of eigenvectors v is unitary if the
matrix a is normal, i.e., if dot(a, a.H) = dot(a.H, a), where a.H denotes the conjugate transpose of
a.
Finally, it is emphasized that v consists of the right (as in right-hand side) eigenvectors of a. A vector y satisfying
dot(y.T, a) = z * y.T for some number z is called a left eigenvector of a, and, in general, the left and
right eigenvectors of a matrix are not necessarily the (perhaps conjugate) transposes of each other.
References
G. Strang, Linear Algebra and Its Applications, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, Various pp.
Examples
Real matrix possessing complex e-values and e-vectors; note that the e-values are complex conjugates of each
other.
Complex-valued matrix with real e-values (but complex-valued e-vectors); note that a.conj().T = a, i.e., a is
Hermitian.
eigh(a, UPLO=L)
Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix.
Returns two objects, a 1-D array containing the eigenvalues of a, and a 2-D square array or matrix (depending
on the input type) of the corresponding eigenvectors (in columns).
Parameters
a : array_like, shape (M, M)
A complex Hermitian or real symmetric matrix.
UPLO : {L, U}, optional
Specifies whether the calculation is done with the lower triangular part of a (L, default)
or the upper triangular part (U).
Returns
w : ndarray, shape (M,)
The eigenvalues, not necessarily ordered.
v : ndarray, or matrix object if a is, shape (M, M)
The column v[:, i] is the normalized eigenvector corresponding to the eigenvalue
w[i].
Raises
LinAlgError :
If the eigenvalue computation does not converge.
See Also:
eigvalsh
eigenvalues of symmetric or Hermitian arrays.
eig
eigenvalues and right eigenvectors for non-symmetric arrays.
eigvals
eigenvalues of non-symmetric arrays.
Notes
This is a simple interface to the LAPACK routines dsyevd and zheevd, which compute the eigenvalues and
eigenvectors of real symmetric and complex Hermitian arrays, respectively.
The eigenvalues of real symmetric or complex Hermitian matrices are always real. [R47] The array v of (column)
eigenvectors is unitary and a, w, and v satisfy the equations dot(a, v[:, i]) = w[i] * v[:, i].
References
[R47]
Examples
>>> np.dot(a, v[:, 0]) - w[0] * v[:, 0] # verify 1st e-val/vec pair
array([2.77555756e-17 + 0.j, 0. + 1.38777878e-16j])
>>> np.dot(a, v[:, 1]) - w[1] * v[:, 1] # verify 2nd e-val/vec pair
array([ 0.+0.j, 0.+0.j])
eigvals(a)
Compute the eigenvalues of a general matrix.
Main difference between eigvals and eig: the eigenvectors arent returned.
Parameters
a : array_like, shape (M, M)
A complex- or real-valued matrix whose eigenvalues will be computed.
Returns
w : ndarray, shape (M,)
The eigenvalues, each repeated according to its multiplicity. They are not necessarily
ordered, nor are they necessarily real for real matrices.
Raises
LinAlgError :
If the eigenvalue computation does not converge.
See Also:
eig
eigenvalues and right eigenvectors of general arrays
eigvalsh
eigenvalues of symmetric or Hermitian arrays.
eigh
eigenvalues and eigenvectors of symmetric/Hermitian arrays.
Notes
This is a simple interface to the LAPACK routines dgeev and zgeev that sets those routines flags to return only
the eigenvalues of general real and complex arrays, respectively.
Examples
Illustration, using the fact that the eigenvalues of a diagonal matrix are its diagonal elements, that multiplying
a matrix on the left by an orthogonal matrix, Q, and on the right by Q.T (the transpose of Q), preserves the
eigenvalues of the middle matrix. In other words, if Q is orthogonal, then Q * A * Q.T has the same
eigenvalues as A:
Now multiply a diagonal matrix by Q on one side and by Q.T on the other:
>>> D = np.diag((-1,1))
>>> LA.eigvals(D)
array([-1., 1.])
>>> A = np.dot(Q, D)
>>> A = np.dot(A, Q.T)
>>> LA.eigvals(A)
array([ 1., -1.])
eigvalsh(a, UPLO=L)
Compute the eigenvalues of a Hermitian or real symmetric matrix.
Main difference from eigh: the eigenvectors are not computed.
Parameters
a : array_like, shape (M, M)
A complex- or real-valued matrix whose eigenvalues are to be computed.
UPLO : {L, U}, optional
Specifies whether the calculation is done with the lower triangular part of a (L, default)
or the upper triangular part (U).
Returns
w : ndarray, shape (M,)
The eigenvalues, not necessarily ordered, each repeated according to its multiplicity.
Raises
LinAlgError :
If the eigenvalue computation does not converge.
See Also:
eigh
eigenvalues and eigenvectors of symmetric/Hermitian arrays.
eigvals
eigenvalues of general real or complex arrays.
eig
eigenvalues and right eigenvectors of general real or complex arrays.
Notes
This is a simple interface to the LAPACK routines dsyevd and zheevd that sets those routines flags to return
only the eigenvalues of real symmetric and complex Hermitian arrays, respectively.
Examples
Notes
For values of ord <= 0, the result is, strictly speaking, not a mathematical norm, but it may still be useful
for various numerical purposes.
The following norms can be calculated:
ord norm for matrices norm for vectors
None Frobenius norm 2-norm
fro Frobenius norm
inf max(sum(abs(x), axis=1)) max(abs(x))
-inf min(sum(abs(x), axis=1)) min(abs(x))
0 sum(x != 0)
1 max(sum(abs(x), axis=0)) as below
-1 min(sum(abs(x), axis=0)) as below
2 2-norm (largest sing. value) as below
-2 smallest singular value as below
other sum(abs(x)**ord)**(1./ord)
The Frobenius norm is given by [R48]:
||A||F = [ i,j abs(ai,j )2 ]1/2
P
References
[R48]
Examples
>>> LA.norm(a)
7.745966692414834
>>> LA.norm(b)
7.745966692414834
>>> LA.norm(b, fro)
7.745966692414834
>>> LA.norm(a, np.inf)
4
>>> LA.norm(b, np.inf)
9
>>> LA.norm(a, -np.inf)
0
>>> LA.norm(b, -np.inf)
2
>>> LA.norm(a, 1)
20
>>> LA.norm(b, 1)
7
>>> LA.norm(a, -1)
-4.6566128774142013e-010
>>> LA.norm(b, -1)
6
>>> LA.norm(a, 2)
7.745966692414834
>>> LA.norm(b, 2)
7.3484692283495345
cond(x, p=None)
Compute the condition number of a matrix.
This function is capable of returning the condition number using one of seven different norms, depending on the
value of p (see Parameters below).
Parameters
x : array_like, shape (M, N)
The matrix whose condition number is sought.
p : {None, 1, -1, 2, -2, inf, -inf, fro}, optional
Order of the norm:
Notes
The condition number of x is defined as the norm of x times the norm of the inverse of x [R46]; the norm can be
the usual L2-norm (root-of-sum-of-squares) or one of a number of other matrix norms.
References
[R46]
Examples
det(a)
Compute the determinant of an array.
Parameters
a : array_like, shape (M, M)
Input array.
Returns
det : ndarray
Determinant of a.
See Also:
slogdet
Another way to representing the determinant, more suitable for large matrices where underflow/overflow
may occur.
Notes
The determinant is computed via LU factorization using the LAPACK routine z/dgetrf.
Examples
The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
slogdet(a)
Compute the sign and (natural) logarithm of the determinant of an array.
If an array has a very small or very large determinant, than a call to det may overflow or underflow. This
routine is more robust against such issues, because it computes the logarithm of the determinant rather than the
determinant itself.
Parameters
a : array_like, shape (M, M)
Input array.
Returns
sign : float or complex
A number representing the sign of the determinant. For a real matrix, this is 1, 0, or -1.
For a complex matrix, this is a complex number with absolute value 1 (i.e., it is on the
unit circle), or else 0.
logdet : float
The natural log of the absolute value of the determinant.
If the determinant is zero, then sign will be 0 and logdet will be :
-Inf. In all cases, the determinant is equal to sign * np.exp(logdet). :
See Also:
det
Notes
The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. New in version 2.0.0..
Examples
The determinant of a 2-D array [[a, b], [c, d]] is ad - bc:
See Also:
diag, diagonal, diagflat
Examples
>>> np.trace(np.eye(3))
3.0
>>> a = np.arange(8).reshape((2,2,2))
>>> np.trace(a)
array([6, 8])
>>> a = np.arange(24).reshape((2,2,2,3))
>>> np.trace(a).shape
(2, 3)
Notes
solve is a wrapper for the LAPACK routines dgesv and zgesv, the former being used if a is real-valued, the latter
if it is complex-valued. The solution to the system of linear equations is computed using an LU decomposition
[R50] with partial pivoting and row interchanges.
a must be square and of full-rank, i.e., all rows (or, equivalently, columns) must be linearly independent; if either
is not true, use lstsq for the least-squares best solution of the system/equation.
References
[R50]
Examples
Solve the system of equations 3 * x0 + x1 = 9 and x0 + 2 * x1 = 8:
tensorsolve(a, b, axes=None)
Solve the tensor equation a x = b for x.
It is assumed that all indices of x are summed over in the product, together with the rightmost indices of a, as is
done in, for example, tensordot(a, x, axes=len(b.shape)).
Parameters
a : array_like
Coefficient tensor, of shape b.shape + Q. Q, a tuple, equals the shape of that
sub-tensor of a consisting of the appropriate number of its rightmost indices, and
must be such that
prod(Q) == prod(b.shape) (in which sense a is said to be square).
b : array_like
Right-hand tensor, which can be of any shape.
axes : tuple of ints, optional
Axes in a to reorder to the right, before inversion. If None (default), no reordering is
done.
Returns
x : ndarray, shape Q
Raises
LinAlgError :
If a is singular or not square (in the above sense).
See Also:
tensordot, tensorinv
Examples
>>> a = np.eye(2*3*4)
>>> a.shape = (2*3, 4, 2, 3, 4)
>>> b = np.random.randn(2*3, 4)
>>> x = np.linalg.tensorsolve(a, b)
>>> x.shape
(2, 3, 4)
>>> np.allclose(np.tensordot(a, x, axes=3), b)
True
lstsq(a, b, rcond=-1)
Return the least-squares solution to a linear matrix equation.
Solves the equation a x = b by computing a vector x that minimizes the norm || b - a x ||. The equation may
be under-, well-, or over- determined (i.e., the number of linearly independent rows of a can be less than, equal
to, or greater than its number of linearly independent columns). If a is square and of full rank, then x (but for
round-off error) is the exact solution of the equation.
Parameters
a : array_like, shape (M, N)
Coefficient matrix.
b : array_like, shape (M,) or (M, K)
Ordinate or dependent variable values. If b is two-dimensional, the least-squares
solution is calculated for each of the K columns of b.
rcond : float, optional
Cut-off ratio for small singular values of a. Singular values are set to zero if they are
smaller than rcond times the largest singular value of a.
Returns
x : ndarray, shape (N,) or (N, K)
Least-squares solution. The shape of x depends on the shape of b.
residues : ndarray, shape (), (1,), or (K,)
Sums of residues; squared Euclidean norm for each column in b - a*x. If the rank of
a is < N or > M, this is an empty array. If b is 1-dimensional, this is a (1,) shape array.
Otherwise the shape is (K,).
rank : int
Rank of matrix a.
s : ndarray, shape (min(M,N),)
Singular values of a.
Raises
LinAlgError :
If computation does not converge.
Notes
If b is a matrix, then all array results are returned as matrices.
Examples
Fit a line, y = mx + c, through some noisy data-points:
By examining the coefficients, we see that the line should have a gradient of roughly 1 and cut the y-axis at,
more or less, -1.
We can rewrite the line equation as y = Ap, where A = [[x 1]] and p = [[m], [c]]. Now use lstsq
to solve for p:
2.5
Original data
2.0 Fitted line
1.5
1.0
0.5
0.0
0.5
1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0
inv(a)
Compute the (multiplicative) inverse of a matrix.
Given a square matrix a, return the matrix ainv satisfying dot(a, ainv) = dot(ainv, a) =
eye(a.shape[0]).
Parameters
a : array_like, shape (M, M)
Matrix to be inverted.
Returns
ainv : ndarray or matrix, shape (M, M)
(Multiplicative) inverse of the matrix a.
Raises
LinAlgError :
If a is singular or not square.
Examples
pinv(a, rcond=1.0000000000000001e-15)
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
Calculate the generalized inverse of a matrix using its singular-value decomposition (SVD) and including all
large singular values.
Parameters
a : array_like, shape (M, N)
Matrix to be pseudo-inverted.
rcond : float
Cutoff for small singular values. Singular values smaller (in modulus) than rcond *
largest_singular_value (again, in modulus) are set to zero.
Returns
B : ndarray, shape (N, M)
The pseudo-inverse of a. If a is a matrix instance, then so is B.
Raises
LinAlgError :
If the SVD computation does not converge.
Notes
The pseudo-inverse of a matrix A, denoted A+ , is defined as: the matrix that solves [the least-squares prob-
lem] Ax = b, i.e., if x is said solution, then A+ is that matrix such that x = A+ b.
It can be shown that if Q1 QT2 = A is the singular value decomposition of A, then A+ = Q2 + QT1 , where
Q1,2 are orthogonal matrices, is a diagonal matrix consisting of As so-called singular values, (followed,
typically, by zeros), and then + is simply the diagonal matrix consisting of the reciprocals of As singular
values (again, followed by zeros). [R49]
References
[R49]
Examples
The following example checks that a * a+ * a == a and a+ * a * a+ == a+:
>>> a = np.random.randn(9, 6)
>>> B = np.linalg.pinv(a)
>>> np.allclose(a, np.dot(a, np.dot(B, a)))
True
>>> np.allclose(B, np.dot(B, np.dot(a, B)))
True
tensorinv(a, ind=2)
Compute the inverse of an N-dimensional array.
The result is an inverse for a relative to the tensordot operation tensordot(a, b, ind), i. e., up to
floating-point accuracy, tensordot(tensorinv(a), a, ind) is the identity tensor for the tensordot
operation.
Parameters
a : array_like
Tensor to invert. Its shape must be square, i. e., prod(a.shape[:ind]) ==
prod(a.shape[ind:]).
ind : int, optional
Number of first indices that are involved in the inverse sum. Must be a positive integer,
default is 2.
Returns
b : ndarray
as tensordot inverse, shape a.shape[:ind] + a.shape[ind:].
Raises
LinAlgError :
If a is singular or not square (in the above sense).
See Also:
tensordot, tensorsolve
Examples
>>> a = np.eye(4*6)
>>> a.shape = (4, 6, 8, 3)
>>> ainv = np.linalg.tensorinv(a, ind=2)
>>> ainv.shape
(8, 3, 4, 6)
>>> b = np.random.randn(4, 6)
>>> np.allclose(np.tensordot(ainv, b), np.linalg.tensorsolve(a, b))
True
>>> a = np.eye(4*6)
>>> a.shape = (24, 8, 3)
>>> ainv = np.linalg.tensorinv(a, ind=1)
>>> ainv.shape
(8, 3, 24)
>>> b = np.random.randn(24)
3.7.6 Exceptions
Examples
See Also:
random
Notes
This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer to
random.
Examples
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
random.standard_normal
Similar, but takes a tuple as its argument.
Notes
For random samples from N (, 2 ), use:
sigma * np.random.randn(...) + mu
Examples
>>> np.random.randn()
2.1923875335537315 #random
random.random_integers
similar to randint, only for the closed interval [low, high], and 1 is the lowest value if high is omitted. In
particular, this other one is the one to use to generate uniformly distributed discrete non-integers.
Examples
random.randint
Similar to random_integers, only for the half-open interval [low, high), and 0 is the lowest value if high is
omitted.
Notes
To sample from N evenly spaced floating-point numbers between a and b, use:
a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)
Examples
>>> np.random.random_integers(5)
4
>>> type(np.random.random_integers(5))
<type int>
>>> np.random.random_integers(5, size=(3.,2.))
array([[5, 4],
[3, 3],
[4, 5]])
Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (i.e., from
the set 0, 5/8, 10/8, 15/8, 20/8):
Roll two six sided dice 1000 times and sum the results:
0.20
0.15
0.10
0.05
0.00
2 4 6 8 10 12
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the continuous uniform distribution over the stated interval. To sample U nif [a, b), b > a
multiply the output of random_sample by (b-a) and add a:
(b - a) * random_sample() + a
Parameters
size : int or tuple of ints, optional
Defines the shape of the returned array of random floats. If None (the default), returns
a single float.
Returns
out : float or ndarray of floats
Array of random floats of shape size (unless size=None, in which case a single float
is returned).
Examples
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type float>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
bytes(length)
Return random bytes.
Parameters
length : int
Number of random bytes.
Returns
out : str
String of length N.
Examples
>>> np.random.bytes(10)
eh\x85\x022SZ\xbf\xa4 #random
3.8.2 Permutations
Examples
>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
3.8.3 Distributions
beta(a, b, size=None)
The Beta distribution over [0, 1].
The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution. It
has the probability distribution function
1
f (x; a, b) = x1 (1 x)1 ,
B(, )
scipy.stats.distributions.binom
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Binomial distribution is
n N
P (N ) = p (1 p)nN ,
N
where n is the number of trials, p is the probability of success, and N is the number of successes.
When estimating the standard error of a proportion in a population by using a random sample, the normal
distribution works well unless the product p*n <=5, where p = population proportion estimate, and n = number
of samples, in which case the binomial distribution is used instead. For example, a sample of 15 people shows
4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so the binomial
distribution should be used in this case.
References
[R69], [R70], [R71], [R72], [R73]
Examples
Draw samples from the distribution:
A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability of
success of 0.1. All nine wells fail. What is the probability of that happening?
Lets do 20,000 trials of the model, and count the number that generate zero positive results.
>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.
chisquare(df, size=None)
Draw samples from a chi-square distribution.
When df independent random variables, each with standard normal distributions (mean 0, variance 1), are
squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in
hypothesis testing.
Parameters
df : int
Number of degrees of freedom.
size : tuple of ints, int, optional
Size of the returned array. By default, a scalar is returned.
Returns
output : ndarray
Samples drawn from the distribution, packed in a size-shaped array.
Raises
ValueError :
When df <= 0 or when an inappropriate size (e.g. size=-1) is given.
Notes
The variable obtained by summing the squares of df independent, standard normally distributed random vari-
ables:
df
X
Q= Xi2
i=0
References
[R74], [R75]
Examples
>>> np.random.chisquare(2,4)
array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272])
dirichlet(alpha, size=None)
Draw samples from the Dirichlet distribution.
Draw size samples of dimension k from a Dirichlet distribution. A Dirichlet-distributed random variable can be
seen as a multivariate generalization of a Beta distribution. Dirichlet pdf is the conjugate prior of a multinomial
in Bayesian inference.
Parameters
alpha : array
Parameter of the distribution (k dimension for sample of dimension k).
size : array
Number of samples to draw.
Notes
k
Y
i 1
X x
i
i=1
Uses the following property for computation: for each dimension, draw a random sample y_i from a standard
gamma generator of shape alpha_i, then X = Pk1 y (y1 , . . . , yn ) is Dirichlet distributed.
i=1 i
References
[R235]
exponential(scale=1.0, size=None)
Exponential distribution.
Its probability density function is
1 1 x
f (x; ) = exp( ),
for x > 0 and 0 elsewhere. is the scale parameter, which is the inverse of the rate parameter = 1/. The
rate parameter is an alternative, widely used parameterization of the exponential distribution [R78].
The exponential distribution is a continuous analogue of the geometric distribution. It describes many common
situations, such as the size of raindrops measured over many rainstorms [R76], or the time between page requests
to Wikipedia [R77].
Parameters
scale : float
The scale parameter, = 1/.
size : tuple of ints
Number of samples to draw. The output is shaped according to size.
References
[R76], [R77], [R78]
f(dfnum, dfden, size=None)
Draw samples from a F distribution.
Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in numerator)
and dfden (degrees of freedom in denominator), where both parameters should be greater than zero.
The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability
distribution that arises in ANOVA tests, and is the ratio of two chi-square variates.
Parameters
dfnum : float
Degrees of freedom in numerator. Should be greater than zero.
dfden : float
Degrees of freedom in denominator. Should be greater than zero.
size : {tuple, int}, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn. By default only one sample is returned.
Returns
samples : {ndarray, scalar}
Samples from the Fisher distribution.
See Also:
scipy.stats.distributions.f
probability density function, distribution or cumulative density function, etc.
Notes
The F statistic is used to compare in-group variances to between-group variances. Calculating the distribution
depends on the sampling, and so it is a function of the respective degrees of freedom in the problem. The
variable dfnum is the number of samples minus one, the between-groups degrees of freedom, while dfden is the
within-groups degrees of freedom, the sum of the number of samples in each group minus the number of groups.
References
[R79], [R80]
Examples
An example from Glantz[1], pp 47-40. Two groups, children of diabetics (25 people) and children from people
without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value of 86.1,
controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are these data consistent
with the null hypothesis that the parents diabetic status does not affect their childrens blood glucose levels?
Calculating the F statistic from the data gives a value of 36.01.
>>> sort(s)[-10]
7.61988120985
So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null hypothesis
is rejected at the 1% level.
gamma(shape, scale=1.0, size=None)
Draw samples from a Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated k)
and scale (sometimes designated theta), where both parameters are > 0.
Parameters
shape : scalar > 0
The shape of the gamma distribution.
scale : scalar > 0, optional
The scale of the gamma distribution. Default is equal to 1.
size : shape_tuple, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
out : ndarray, float
Returns one sample unless size parameter is specified.
See Also:
scipy.stats.distributions.gamma
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gamma distribution is
ex/
p(x) = xk1 ,
k (k)
where k is the shape and the scale, and is the Gamma function.
The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally
in processes for which the waiting times between Poisson distributed events are relevant.
References
[R81], [R82]
Examples
geometric(p, size=None)
Draw samples from the geometric distribution.
Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an experiment
is flipping a coin). The geometric distribution models the number of trials that must be run in order to achieve
success. It is therefore supported on the positive integers, k = 1, 2, ....
The probability mass function of the geometric distribution is
f (k) = (1 p)k1 p
Examples
Draw ten thousand values from the geometric distribution, with the probability of an individual success equal to
0.35:
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
See Also:
scipy.stats.gumbel
probability density function, distribution or cumulative density function, etc.
weibull, scipy.stats.genextreme
Notes
The probability density for the Gumbel distribution is
e(x)/ e(x)/
p(x) = e ,
References
[R83], [R84], [R85]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian:
>>> means = []
>>> maxima = []
>>> for i in range(0,1000) :
... a = np.random.normal(mu, beta, 1000)
... means.append(a.mean())
... maxima.append(a.max())
14
12
10
8
6
4
2
0
0.4 0.2 0.0 0.2 0.4 0.6 0.8
scipy.stats.distributions.hypergeom
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Hypergeometric distribution is
m N m
n nx
P (x) = N
,
n
where 0 x m and n + m N x n
for P(x) the probability of x successes, n = ngood, m = nbad, and N = number of samples.
Consider an urn with black and white marbles in it, ngood of them black and nbad are white. If you draw
nsample balls without replacement, then the Hypergeometric distribution describes the distribution of black
balls in the drawn sample.
Note that this distribution is very similar to the Binomial distribution, except that in this case, samples are drawn
without replacement, whereas in the Binomial case samples are drawn with replacement (or the sample space is
infinite). As the sample space becomes large, this distribution approaches the Binomial.
References
[R86], [R87], [R88]
Examples
Draw samples from the distribution:
Suppose you have an urn with 15 white and 15 black marbles. If you pull 15 marbles at random, how likely is
it that 12 or more of them are one color?
Notes
It has the probability density function
1 |x |
f (x; , ) = exp .
2
The first law of Laplace, from 1774, states that the frequency of an error can be expressed as an exponential
function of the absolute magnitude of the error, which leads to the Laplace distribution. For many problems
in Economics and Health sciences, this distribution seems to model the data better than the standard Gaussian
distribution
References
[R89], [R90], [R91], [R92]
Examples
Draw samples from the distribution
Display the histogram of the samples, along with the probability density function:
0.5
0.4
0.3
0.2
0.1
0.0
8 6 4 2 0 2 4 6 8
scipy.stats.distributions.logistic
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Logistic distribution is
e(x)/s
P (x) = P (x) = ,
s(1 + e(x)/s )2
References
[R93], [R94], [R95]
Examples
Draw samples from the distribution:
scipy.stats.lognorm
probability density function, distribution, cumulative density function, etc.
Notes
A variable x has a log-normal distribution if log(x) is normally distributed.
The probability density function for the log-normal distribution is
1 (ln(x))2
p(x) = e( 22 )
x 2
where is the mean and is the standard deviation of the normally distributed logarithm of the variable.
A log-normal distribution results if a random variable is the product of a large number of independent,
identically-distributed variables in the same way that a normal distribution results if the variable is the sum of a
large number of independent, identically-distributed variables (see the last example). It is one of the so-called
fat-tailed distributions.
The log-normal distribution is commonly used to model the lifespan of units with fatigue-stress failure modes.
Since this includes most mechanical systems, the log-normal distribution has widespread application.
It is also commonly used to model oil field sizes, species abundance, and latent periods of infectious diseases.
References
[R96], [R97], [R98]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
Demonstrate that taking the products of random samples from a uniform distribution can be fit well by a log-
normal probability density function.
0.035
0.030
0.025
0.020
0.015
0.010
0.005
0.000
50 100 150 200 250 300
logseries(p, size=None)
Draw samples from a Logarithmic Series distribution.
Samples are drawn from a Log Series distribution with specified parameter, p (probability, 0 < p < 1).
Parameters
loc : float
scale : float > 0.
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : {ndarray, scalar}
where the values are all integers in [0, n].
See Also:
scipy.stats.distributions.logser
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Log Series distribution is
pk
P (k) = ,
k ln(1 p)
where p = probability.
The Log Series distribution is frequently used to represent species richness and occurrence, first proposed by
Fisher, Corbet, and Williams in 1943 [2]. It may also be used to model the numbers of occupants seen in cars
[3].
References
[R99], [R100], [R101], [R102]
Examples
Draw samples from the distribution:
>>> a = .6
>>> s = np.random.logseries(a, 10000)
>>> count, bins, ignored = plt.hist(s)
Examples
Throw a dice 20 times:
For the first run, we threw 3 times 1, 4 times 2, etc. For the second, we threw 2 times 1, 4 times 2, etc.
A loaded dice is more likely to land on number 6:
Notes
The mean is a coordinate in N-dimensional space, which represents the location where samples are most likely
to be generated. This is analogous to the peak of the bell curve for the one-dimensional or univariate normal
distribution.
Covariance indicates the level to which two variables vary together. From the multivariate normal distribution,
we draw N-dimensional samples, X = [x1 , x2 , ...xN ]. The covariance matrix element Cij is the covariance of
xi and xj . The element Cii is the variance of xi (i.e. its spread).
Instead of specifying the full covariance matrix, popular approximations include:
Spherical covariance (cov is a multiple of the identity matrix)
Diagonal covariance (cov has non-negative elements, and only on the diagonal)
This geometrical property can be seen in two dimensions by plotting generated data-points:
References
[R236], [R237]
Examples
The following is probably true, given that 0.6 is roughly twice the standard deviation:
negative_binomial(n, p, size=None)
Draw samples from a negative_binomial distribution.
Samples are drawn from a negative_Binomial distribution with specified parameters, n trials and p probability
of success where n is an integer > 0 and p is in the interval [0, 1].
Parameters
n : int
Parameter, > 0.
p : float
Parameter, >= 0 and <=1.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : int or ndarray of ints
Drawn samples.
Notes
The probability density for the Negative Binomial distribution is
N +n1 n
P (N ; n, p) = p (1 p)N ,
n1
where n 1 is the number of successes, p is the probability of success, and N + n 1 is the number of trials.
The negative binomial distribution gives the probability of n-1 successes and N failures in N+n-1 trials, and
success on the (N+n)th trial.
If one throws a die repeatedly until the third time a 1 appears, then the probability distribution of the number
of non-1s that appear before the third 1 is a negative binomial distribution.
References
[R238], [R239]
Examples
Draw samples from the distribution:
A real world example. A company drills wild-cat oil exploration wells, each with an estimated probability
of success of 0.1. What is the probability of having one success for each successive well, that is what is the
probability of a single success after drilling 5 wells, after 6 wells, etc.?
Notes
The probability density function for the noncentral Chi-square distribution is
X enonc/2 (nonc/2)i
P (x; df, nonc) = PYdf +2i (x),
i=0
i!
References
[R240], [R241]
Examples
Draw values from the distribution and plot the histogram
Draw values from a noncentral chisquare with very small noncentrality, and compare to a chisquare.
>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),
... bins=np.arange(0., 25, .1), normed=True)
>>> values2 = plt.hist(np.random.chisquare(3, 100000),
... bins=np.arange(0., 25, .1), normed=True)
>>> plt.plot(values[1][0:-1], values[0]-values2[0], ob)
>>> plt.show()
>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
... bins=200, normed=True)
>>> plt.show()
0.05
0.04
0.03
0.02
0.01
0.00
0 10 20 30 40 50 60 70 80
0.25
0.20
0.15
0.10
0.05
0.00
0 5 10 15 20 25
0.05
0.04
0.03
0.02
0.01
0.00
0 10 20 30 40 50 60 70 80 90
Notes
When calculating the power of an experiment (power = probability of rejecting the null hypothesis when a
specific alternative is true) the non-central F statistic becomes important. When the null hypothesis is true, the
F statistic follows a central F distribution. When the null hypothesis is not true, then it follows a non-central F
statistic.
References
Weisstein, Eric W. Noncentral F-Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/NoncentralF-Distribution.html
Wikipedia, Noncentral F distribution, http://en.wikipedia.org/wiki/Noncentral_F-distribution
Examples
In a study, testing for a specific alternative to the null hypothesis requires use of the Noncentral F distribution.
We need to calculate the area in the tail of the distribution that exceeds the value of the F distribution for the null
hypothesis. Well plot the two probability distributions for comparison.
scipy.stats.distributions.norm
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gaussian distribution is
1 (x)2
p(x) = e 2 2 ,
2 2
where is the mean and the standard deviation. The square of the standard deviation, 2 , is called the
variance.
The function has its peak at the mean, and its spread increases with the standard deviation (the function
reaches 0.607 times its maximum at x + and x [R243]). This implies that numpy.random.normal is
more likely to return samples lying close to the mean, rather than those far away.
References
[R242], [R243]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
0
0.4 0.3 0.2 0.1 0.0 0.1 0.2 0.3
pareto(a, size=None)
Draw samples from a Pareto distribution with specified shape.
This is a simplified version of the Generalized Pareto distribution (available in SciPy), with the scale set to one
and the location set to zero. Most authors default the location to one.
The Pareto distribution must be greater than zero, and is unbounded above. It is also known as the 80-20 rule.
In this distribution, 80 percent of the weights are in the lowest 20 percent of the range, while the other 20 percent
fill the remaining 80 percent of the range.
Parameters
shape : float, > 0.
Shape of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
See Also:
scipy.stats.distributions.genpareto.pdf
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Pareto distribution is
ama
p(x) =
xa+1
References
[R244], [R245], [R246], [R247]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
2.5
2.0
1.5
1.0
0.5
0.0
0 2 4 6 8 10 12 14 16 18
poisson(lam=1.0, size=None)
Draw samples from a Poisson distribution.
The Poisson distribution is the limit of the Binomial distribution for large N.
Parameters
lam : float
Expectation of interval, should be >= 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Notes
The Poisson distribution
k e
f (k; ) =
k!
For events with an expected separation the Poisson distribution f (k; ) describes the probability of k events
occurring within the observed interval .
References
[R248], [R249]
Examples
Draw samples from the distribution:
0.30
0.25
0.20
0.15
0.10
0.05
0.00
0 2 4 6 8 10 12 14 16 18
power(a, size=None)
Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
Also known as the power function distribution.
Parameters
a : float
parameter, > 0
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then
m * n * k samples are drawn.
Returns
samples : {ndarray, scalar}
The returned samples lie in [0, 1].
Raises
ValueError :
If a<1.
Notes
The probability density function is
The power function distribution is just the inverse of the Pareto distribution. It may also be seen as a special
case of the Beta distribution.
It is used, for example, in modeling the over-reporting of insurance claims.
References
[R250], [R251]
Examples
rayleigh(scale=1.0, size=None)
Draw samples from a Rayleigh distribution.
The and Weibull distributions are generalizations of the Rayleigh.
Parameters
scale : scalar
Scale, also equals the mode. Should be >= 0.
size : int or tuple of ints, optional
Shape of the output. Default is None, in which case a single value is returned.
Notes
The probability density function for the Rayleigh distribution is
x x2
P (x; scale) = 2
e 2scale2
scale
The Rayleigh distribution arises if the wind speed and wind direction are both gaussian variables, then the
vector wind velocity forms a Rayleigh distribution. The Rayleigh distribution is used to model the expected
output from wind turbines.
References
..[1] Brighton Webs Ltd., Rayleigh Distribution,
http://www.brighton-webs.co.uk/distributions/rayleigh.asp
..[2] Wikipedia, Rayleigh distribution
http://en.wikipedia.org/wiki/Rayleigh_distribution
Examples
Draw values from the distribution and plot the histogram
Wave heights tend to follow a Rayleigh distribution. If the mean wave height is 1 meter, what fraction of waves
are likely to be larger than 3 meters?
>>> meanvalue = 1
>>> modevalue = np.sqrt(2 / np.pi) * meanvalue
>>> s = np.random.rayleigh(modevalue, 1000000)
>>> 100.*sum(s>3)/1000000.
0.087300000000000003
standard_cauchy(size=None)
Standard Cauchy distribution with mode = 0.
Also known as the Lorentz distribution.
Parameters
size : int or tuple of ints
Shape of the output.
Returns
samples : ndarray or scalar
The drawn samples.
Notes
The probability density function for the full Cauchy distribution is
1
P (x; x0 , ) =
1 + ( xx
0 2
)
References
..[1] NIST/SEMATECH e-Handbook of Statistical Methods, Cauchy
Distribution, http://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm
..[2] Weisstein, Eric W. Cauchy Distribution. From MathWorldA
Wolfram Web Resource. http://mathworld.wolfram.com/CauchyDistribution.html
..[3] Wikipedia, Cauchy distribution
http://en.wikipedia.org/wiki/Cauchy_distribution
Examples
Draw samples and plot the distribution:
>>> s = np.random.standard_cauchy(1000000)
>>> s = s[(s>-25) & (s<25)] # truncate distribution so it plots well
>>> plt.hist(s, bins=100)
>>> plt.show()
standard_exponential(size=None)
Draw samples from the standard exponential distribution.
standard_exponential is identical to the exponential distribution with a scale parameter of 1.
Parameters
size : int or tuple of ints
Shape of the output.
Returns
out : float or ndarray
Drawn samples.
Examples
Output a 3x8000 array:
standard_gamma(shape, size=None)
Draw samples from a Standard Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated k)
and scale=1.
Parameters
shape : float
Parameter, should be > 0.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : ndarray or scalar
The drawn samples.
See Also:
scipy.stats.distributions.gamma
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gamma distribution is
ex/
p(x) = xk1 ,
k (k)
where k is the shape and the scale, and is the Gamma function.
The Gamma distribution is often used to model the times to failure of electronic components, and arises naturally
in processes for which the waiting times between Poisson distributed events are relevant.
References
[R253], [R254]
Examples
standard_normal(size=None)
Returns samples from a Standard Normal distribution (mean=0, stdev=1).
Parameters
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
Returns
out : float or ndarray
Drawn samples.
Examples
>>> s = np.random.standard_normal(8000)
>>> s
array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, #random
-0.38672696, -0.4685006 ]) #random
>>> s.shape
(8000,)
>>> s = np.random.standard_normal(size=(3, 4, 2))
>>> s.shape
(3, 4, 2)
standard_t(df, size=None)
Standard Students t distribution with df degrees of freedom.
A special case of the hyperbolic distribution. As df gets large, the result resembles that of the standard normal
distribution (standard_normal).
Parameters
df : int
Degrees of freedom, should be > 0.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
Returns
samples : ndarray or scalar
Drawn samples.
Notes
The probability density function for the t distribution is
The t test is based on an assumption that the data come from a Normal distribution. The t test provides a way to
test whether the sample mean (that is the mean calculated from the data) is a good estimate of the true mean.
The derivation of the t-distribution was forst published in 1908 by William Gisset while working for the Guin-
ness Brewery in Dublin. Due to proprietary issues, he had to publish under a pseudonym, and so he used the
name Student.
References
[R255], [R256]
Examples
triangular(left, mode, right, size=None)
Draw samples from the triangular distribution.
The triangular distribution is a continuous probability distribution with lower limit left, peak at mode, and upper
limit right. Unlike the other distributions, these parameters directly define the shape of the pdf.
Parameters
left : scalar
Lower limit.
mode : scalar
The value where the peak of the distribution occurs. The value should fulfill the condi-
tion left <= mode <= right.
right : scalar
Upper limit, should be larger than left.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
Returns
samples : ndarray or scalar
The returned samples all lie in the interval [left, right].
Notes
The probability density function for the Triangular distribution is
2(xl)
(rl)(ml) for l x m,
2(mx)
P (x; l, m, r) = (rl)(rm) for m x r,
0 otherwise.
The triangular distribution is often used in ill-defined problems where the underlying distribution is not known,
but some knowledge of the limits and mode exists. Often it is used in simulations.
References
..[1] Wikipedia, Triangular distribution
http://en.wikipedia.org/wiki/Triangular_distribution
Examples
Draw values from the distribution and plot the histogram:
0.20
0.15
0.10
0.05
0.00
4 2 0 2 4 6 8
randint
Discrete uniform distribution, yielding integers.
random_integers
Discrete uniform distribution over the closed interval [low, high].
random_sample
Floats uniformly distributed over [0, 1).
random
Alias for random_sample.
rand
Convenience function that accepts dimensions as input, e.g., rand(2,2) would generate a 2-by-2 array
of floats, uniformly distributed over [0, 1).
Notes
The probability density function of the uniform distribution is
1
p(x) =
ba
Examples
Draw samples from the distribution:
>>> s = np.random.uniform(-1,0,1000)
Display the histogram of the samples, along with the probability density function:
1.2
1.0
0.8
0.6
0.4
0.2
0.0
1.0 0.8 0.6 0.4 0.2 0.0
Samples are drawn from a von Mises distribution with specified mode (mu) and dispersion (kappa), on the
interval [-pi, pi].
The von Mises distribution (also known as the circular normal distribution) is a continuous probability distribu-
tion on the circle. It may be thought of as the circular analogue of the normal distribution.
Parameters
mu : float
Mode (center) of the distribution.
kappa : float, >= 0.
Dispersion of the distribution.
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : {ndarray, scalar}
The returned samples live on the unit circle [-pi, pi].
See Also:
scipy.stats.distributions.vonmises
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the von Mises distribution is
ecos(x)
p(x) = ,
2I0 ()
where is the mode and the dispersion, and I0 () is the modified Bessel function of order 0.
The von Mises, named for Richard Edler von Mises, born in Austria-Hungary, in what is now the Ukraine.
He fled to the United States in 1939 and became a professor at Harvard. He worked in probability theory,
aerodynamics, fluid mechanics, and philosophy of science.
References
[R257], [R258], [R259]
Examples
wald(mean, scale, size=None)
Draw samples from a Wald, or Inverse Gaussian, distribution.
As the scale approaches infinity, the distribution becomes more like a Gaussian.
Some references claim that the Wald is an Inverse Gaussian with mean=1, but this is by no means universal.
The Inverse Gaussian distribution was first studied in relationship to Brownian motion. In 1956 M.C.K. Tweedie
used the name Inverse Gaussian because there is an inverse relationship between the time to cover a unit distance
and distance covered in unit time.
Parameters
mean : scalar
Notes
The probability density function for the Wald distribution is
r
scale scale(xmean)2
As noted above the Inverse Gaussian distribution first arise from attempts to model Brownian Motion. It is also a
competitor to the Weibull for use in reliability modeling and modeling stock returns and interest rate processes.
References
..[1] Brighton Webs Ltd., Wald Distribution,
http://www.brighton-webs.co.uk/distributions/wald.asp
..[2] Chhikara, Raj S., and Folks, J. Leroy, The Inverse Gaussian
Distribution: Theory : Methodology, and Applications, CRC Press, 1988.
..[3] Wikipedia, Wald distribution
http://en.wikipedia.org/wiki/Wald_distribution
Examples
Draw values from the distribution and plot the histogram:
0.45
0.40
0.35
0.30
0.25
0.20
0.15
0.10
0.05
0.00
0 10 20 30 40 50 60 70 80
weibull(a, size=None)
Weibull distribution.
Draw samples from a 1-parameter Weibull distribution with the given shape parameter.
X = (ln(U ))1/a
scipy.stats.distributions.weibull
probability density function, distribution or cumulative density function, etc.
gumbel, scipy.stats.distributions.genextreme
Notes
The probability density for the Weibull distribution is
a x a1 (x/)a
p(x) = ( ) e ,
References
[R260], [R261], [R262]
Examples
Draw samples from the distribution:
>>> a = 5. # shape
>>> s = np.random.weibull(a, 1000)
Display the histogram of the samples, along with the probability density function:
250
200
150
100
50
0
0.0 0.5 1.0 1.5 2.0
zipf(a, size=None)
Draw samples from a Zipf distribution.
Samples are drawn from a Zipf distribution with specified parameter (a), where a > 1.
The zipf distribution (also known as the zeta distribution) is a continuous probability distribution that satisfies
Zipfs law, where the frequency of an item is inversely proportional to its rank in a frequency table.
Parameters
a : float
parameter, > 1.
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : {ndarray, scalar}
The returned samples are greater than or equal to one.
See Also:
scipy.stats.distributions.zipf
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Zipf distribution is
xa
p(x) = ,
(a)
References
[R263], [R264], [R265], [R266]
Examples
Notes
The Python stdlib module random also contains a Mersenne Twister pseudo-random number generator with a
number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPy-
aware, has the advantage that it provides a much larger number of probability distributions to choose from.
Methods
beta(a, b, size=None)
The Beta distribution over [0, 1].
The Beta distribution is a special case of the Dirichlet distribution, and is related to the Gamma distribution.
It has the probability distribution function
1
f (x; a, b) = x1 (1 x)1 ,
B(, )
scipy.stats.distributions.binom
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Binomial distribution is
n N
P (N ) = p (1 p)nN ,
N
where n is the number of trials, p is the probability of success, and N is the number of successes.
When estimating the standard error of a proportion in a population by using a random sample, the normal
distribution works well unless the product p*n <=5, where p = population proportion estimate, and n =
number of samples, in which case the binomial distribution is used instead. For example, a sample of 15
people shows 4 who are left handed, and 11 who are right handed. Then p = 4/15 = 27%. 0.27*15 = 4, so
the binomial distribution should be used in this case.
References
[R169], [R170], [R171], [R172], [R173]
Examples
Draw samples from the distribution:
A real world example. A company drills 9 wild-cat oil exploration wells, each with an estimated probability
of success of 0.1. All nine wells fail. What is the probability of that happening?
Lets do 20,000 trials of the model, and count the number that generate zero positive results.
>>> sum(np.random.binomial(9,0.1,20000)==0)/20000.
answer = 0.38885, or 38%.
bytes(length)
Return random bytes.
Parameters
length : int
Number of random bytes.
Returns
out : str
String of length N.
Examples
>>> np.random.bytes(10)
eh\x85\x022SZ\xbf\xa4 #random
chisquare(df, size=None)
Draw samples from a chi-square distribution.
When df independent random variables, each with standard normal distributions (mean 0, variance 1), are
squared and summed, the resulting distribution is chi-square (see Notes). This distribution is often used in
hypothesis testing.
Parameters
df : int
Number of degrees of freedom.
size : tuple of ints, int, optional
Size of the returned array. By default, a scalar is returned.
Returns
output : ndarray
Samples drawn from the distribution, packed in a size-shaped array.
Raises
ValueError :
When df <= 0 or when an inappropriate size (e.g. size=-1) is given.
Notes
The variable obtained by summing the squares of df independent, standard normally distributed random
variables:
df
X
Q= Xi2
i=0
Q 2k .
References
[R174], [R175]
Examples
>>> np.random.chisquare(2,4)
array([ 1.89920014, 9.00867716, 3.13710533, 5.62318272])
dirichlet(alpha, size=None)
Draw samples from the Dirichlet distribution.
Draw size samples of dimension k from a Dirichlet distribution. A Dirichlet-distributed random variable
can be seen as a multivariate generalization of a Beta distribution. Dirichlet pdf is the conjugate prior of a
multinomial in Bayesian inference.
Parameters
alpha : array
Parameter of the distribution (k dimension for sample of dimension k).
size : array
Number of samples to draw.
Notes
k
Y
i 1
X x
i
i=1
Uses the following property for computation: for each dimension, draw a random sample y_i from a
standard gamma generator of shape alpha_i, then X = Pk1 y (y1 , . . . , yn ) is Dirichlet distributed.
i=1 i
References
[R176]
exponential(scale=1.0, size=None)
Exponential distribution.
Its probability density function is
1 1 x
f (x; ) = exp( ),
for x > 0 and 0 elsewhere. is the scale parameter, which is the inverse of the rate parameter = 1/.
The rate parameter is an alternative, widely used parameterization of the exponential distribution [R179].
The exponential distribution is a continuous analogue of the geometric distribution. It describes many
common situations, such as the size of raindrops measured over many rainstorms [R177], or the time
between page requests to Wikipedia [R178].
Parameters
scale : float
The scale parameter, = 1/.
size : tuple of ints
Number of samples to draw. The output is shaped according to size.
References
[R177], [R178], [R179]
f(dfnum, dfden, size=None)
Draw samples from a F distribution.
Samples are drawn from an F distribution with specified parameters, dfnum (degrees of freedom in nu-
merator) and dfden (degrees of freedom in denominator), where both parameters should be greater than
zero.
The random variate of the F distribution (also known as the Fisher distribution) is a continuous probability
distribution that arises in ANOVA tests, and is the ratio of two chi-square variates.
Parameters
dfnum : float
Degrees of freedom in numerator. Should be greater than zero.
dfden : float
Degrees of freedom in denominator. Should be greater than zero.
size : {tuple, int}, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn. By default only one sample is returned.
Returns
samples : {ndarray, scalar}
Samples from the Fisher distribution.
See Also:
scipy.stats.distributions.f
probability density function, distribution or cumulative density function, etc.
Notes
The F statistic is used to compare in-group variances to between-group variances. Calculating the distribu-
tion depends on the sampling, and so it is a function of the respective degrees of freedom in the problem.
The variable dfnum is the number of samples minus one, the between-groups degrees of freedom, while
dfden is the within-groups degrees of freedom, the sum of the number of samples in each group minus the
number of groups.
References
[R180], [R181]
Examples
An example from Glantz[1], pp 47-40. Two groups, children of diabetics (25 people) and children from
people without diabetes (25 controls). Fasting blood glucose was measured, case group had a mean value
of 86.1, controls had a mean value of 82.2. Standard deviations were 2.09 and 2.49 respectively. Are
these data consistent with the null hypothesis that the parents diabetic status does not affect their childrens
blood glucose levels? Calculating the F statistic from the data gives a value of 36.01.
Draw samples from the distribution:
>>> sort(s)[-10]
7.61988120985
So there is about a 1% chance that the F statistic will exceed 7.62, the measured value is 36, so the null
hypothesis is rejected at the 1% level.
gamma(shape, scale=1.0, size=None)
Draw samples from a Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated
k) and scale (sometimes designated theta), where both parameters are > 0.
Parameters
shape : scalar > 0
The shape of the gamma distribution.
scale : scalar > 0, optional
The scale of the gamma distribution. Default is equal to 1.
size : shape_tuple, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
out : ndarray, float
Returns one sample unless size parameter is specified.
See Also:
scipy.stats.distributions.gamma
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gamma distribution is
ex/
p(x) = xk1 ,
k (k)
where k is the shape and the scale, and is the Gamma function.
The Gamma distribution is often used to model the times to failure of electronic components, and arises
naturally in processes for which the waiting times between Poisson distributed events are relevant.
References
[R182], [R183]
Examples
geometric(p, size=None)
Draw samples from the geometric distribution.
Bernoulli trials are experiments with one of two outcomes: success or failure (an example of such an
experiment is flipping a coin). The geometric distribution models the number of trials that must be run in
order to achieve success. It is therefore supported on the positive integers, k = 1, 2, ....
The probability mass function of the geometric distribution is
f (k) = (1 p)k1 p
Examples
Draw ten thousand values from the geometric distribution, with the probability of an individual success
equal to 0.35:
get_state()
Return a tuple representing the internal state of the generator.
For more details, see set_state.
Returns
out : tuple(str, ndarray of 624 uints, int, int, float)
The returned tuple has the following items:
1. the string MT19937.
2. a 1-D array of 624 unsigned integer keys.
3. an integer pos.
4. an integer has_gauss.
5. a float cached_gaussian.
See Also:
set_state
Notes
set_state and get_state are not needed to work with any of the random distributions in NumPy. If the
internal state is manually altered, the user should know exactly what he/she is doing.
gumbel(loc=0.0, scale=1.0, size=None)
Gumbel distribution.
Draw samples from a Gumbel distribution with specified location (or mean) and scale (or standard devia-
tion).
The Gumbel (or Smallest Extreme Value (SEV) or the Smallest Extreme Value Type I) distribution is one
of a class of Generalized Extreme Value (GEV) distributions used in modeling extreme value problems.
The Gumbel is a special case of the Extreme Value Type I distribution for maximums from distributions
with exponential-like tails, it may be derived by considering a Gaussian process of measurements, and
generating the pdf for the maximum values from that set of measurements (see examples).
Parameters
loc : float
The location of the mode of the distribution.
scale : float
The scale parameter of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
See Also:
scipy.stats.gumbel
probability density function, distribution or cumulative density function, etc.
weibull, scipy.stats.genextreme
Notes
The probability density for the Gumbel distribution is
e(x)/ e(x)/
p(x) = e ,
References
[R184], [R185], [R186]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
Show how an extreme value distribution can arise from a Gaussian process and compare to a Gaussian:
>>> means = []
>>> maxima = []
>>> for i in range(0,1000) :
... a = np.random.normal(mu, beta, 1000)
... means.append(a.mean())
... maxima.append(a.max())
>>> count, bins, ignored = plt.hist(maxima, 30, normed=True)
>>> beta = np.std(maxima)*np.pi/np.sqrt(6)
>>> mu = np.mean(maxima) - 0.57721*beta
>>> plt.plot(bins, (1/beta)*np.exp(-(bins - mu)/beta)
... * np.exp(-np.exp(-(bins - mu)/beta)),
... linewidth=2, color=r)
>>> plt.plot(bins, 1/(beta * np.sqrt(2 * np.pi))
... * np.exp(-(bins - mu)**2 / (2 * beta**2)),
... linewidth=2, color=g)
>>> plt.show()
14
12
10
8
6
4
2
0
0.4 0.2 0.0 0.2 0.4 0.6 0.8
Samples are drawn from a Hypergeometric distribution with specified parameters, ngood (ways to make a
good selection), nbad (ways to make a bad selection), and nsample = number of items sampled, which is
less than or equal to the sum ngood + nbad.
Parameters
ngood : float (but truncated to an integer)
parameter, > 0.
nbad : float
parameter, >= 0.
nsample : float
parameter, > 0 and <= ngood+nbad
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : {ndarray, scalar}
where the values are all integers in [0, n].
See Also:
scipy.stats.distributions.hypergeom
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Hypergeometric distribution is
m N m
n nx
P (x) = N
,
n
where 0 x m and n + m N x n
for P(x) the probability of x successes, n = ngood, m = nbad, and N = number of samples.
Consider an urn with black and white marbles in it, ngood of them black and nbad are white. If you
draw nsample balls without replacement, then the Hypergeometric distribution describes the distribution
of black balls in the drawn sample.
Note that this distribution is very similar to the Binomial distribution, except that in this case, samples
are drawn without replacement, whereas in the Binomial case samples are drawn with replacement (or the
sample space is infinite). As the sample space becomes large, this distribution approaches the Binomial.
References
[R187], [R188], [R189]
Examples
Draw samples from the distribution:
Suppose you have an urn with 15 white and 15 black marbles. If you pull 15 marbles at random, how
likely is it that 12 or more of them are one color?
Notes
It has the probability density function
1 |x |
f (x; , ) = exp .
2
The first law of Laplace, from 1774, states that the frequency of an error can be expressed as an exponential
function of the absolute magnitude of the error, which leads to the Laplace distribution. For many prob-
lems in Economics and Health sciences, this distribution seems to model the data better than the standard
Gaussian distribution
References
[R190], [R191], [R192], [R193]
Examples
Draw samples from the distribution
Display the histogram of the samples, along with the probability density function:
0.5
0.4
0.3
0.2
0.1
0.0
8 6 4 2 0 2 4 6 8
scipy.stats.distributions.logistic
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Logistic distribution is
e(x)/s
P (x) = P (x) = ,
s(1 + e(x)/s )2
References
[R194], [R195], [R196]
Examples
Draw samples from the distribution:
scipy.stats.lognorm
probability density function, distribution, cumulative density function, etc.
Notes
A variable x has a log-normal distribution if log(x) is normally distributed.
The probability density function for the log-normal distribution is
1 (ln(x))2
p(x) = e( 22 )
x 2
where is the mean and is the standard deviation of the normally distributed logarithm of the variable.
A log-normal distribution results if a random variable is the product of a large number of independent,
identically-distributed variables in the same way that a normal distribution results if the variable is the sum
of a large number of independent, identically-distributed variables (see the last example). It is one of the
so-called fat-tailed distributions.
The log-normal distribution is commonly used to model the lifespan of units with fatigue-stress failure
modes. Since this includes most mechanical systems, the log-normal distribution has widespread applica-
tion.
It is also commonly used to model oil field sizes, species abundance, and latent periods of infectious
diseases.
References
[R197], [R198], [R199]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
Demonstrate that taking the products of random samples from a uniform distribution can be fit well by a
log-normal probability density function.
0.035
0.030
0.025
0.020
0.015
0.010
0.005
0.000
50 100 150 200 250 300
logseries(p, size=None)
Draw samples from a Logarithmic Series distribution.
Samples are drawn from a Log Series distribution with specified parameter, p (probability, 0 < p < 1).
Parameters
loc : float
scale : float > 0.
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : {ndarray, scalar}
where the values are all integers in [0, n].
See Also:
scipy.stats.distributions.logser
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Log Series distribution is
pk
P (k) = ,
k ln(1 p)
where p = probability.
The Log Series distribution is frequently used to represent species richness and occurrence, first proposed
by Fisher, Corbet, and Williams in 1943 [2]. It may also be used to model the numbers of occupants seen
in cars [3].
References
[R200], [R201], [R202], [R203]
Examples
Draw samples from the distribution:
>>> a = .6
>>> s = np.random.logseries(a, 10000)
>>> count, bins, ignored = plt.hist(s)
Examples
Throw a dice 20 times:
For the first run, we threw 3 times 1, 4 times 2, etc. For the second, we threw 2 times 1, 4 times 2, etc.
A loaded dice is more likely to land on number 6:
Notes
The mean is a coordinate in N-dimensional space, which represents the location where samples are most
likely to be generated. This is analogous to the peak of the bell curve for the one-dimensional or univariate
normal distribution.
Covariance indicates the level to which two variables vary together. From the multivariate normal distri-
bution, we draw N-dimensional samples, X = [x1 , x2 , ...xN ]. The covariance matrix element Cij is the
covariance of xi and xj . The element Cii is the variance of xi (i.e. its spread).
Instead of specifying the full covariance matrix, popular approximations include:
Spherical covariance (cov is a multiple of the identity matrix)
Diagonal covariance (cov has non-negative elements, and only on the diagonal)
This geometrical property can be seen in two dimensions by plotting generated data-points:
References
[R204], [R205]
Examples
The following is probably true, given that 0.6 is roughly twice the standard deviation:
negative_binomial(n, p, size=None)
Draw samples from a negative_binomial distribution.
Samples are drawn from a negative_Binomial distribution with specified parameters, n trials and p proba-
bility of success where n is an integer > 0 and p is in the interval [0, 1].
Parameters
n : int
Parameter, > 0.
p : float
Parameter, >= 0 and <=1.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : int or ndarray of ints
Drawn samples.
Notes
The probability density for the Negative Binomial distribution is
N +n1 n
P (N ; n, p) = p (1 p)N ,
n1
where n 1 is the number of successes, p is the probability of success, and N + n 1 is the number of
trials.
The negative binomial distribution gives the probability of n-1 successes and N failures in N+n-1 trials,
and success on the (N+n)th trial.
If one throws a die repeatedly until the third time a 1 appears, then the probability distribution of the
number of non-1s that appear before the third 1 is a negative binomial distribution.
References
[R206], [R207]
Examples
Draw samples from the distribution:
A real world example. A company drills wild-cat oil exploration wells, each with an estimated probability
of success of 0.1. What is the probability of having one success for each successive well, that is what is
the probability of a single success after drilling 5 wells, after 6 wells, etc.?
Notes
The probability density function for the noncentral Chi-square distribution is
X enonc/2 (nonc/2)i
P (x; df, nonc) = PYdf +2i (x),
i=0
i!
In Delhi (2007), it is noted that the noncentral chi-square is useful in bombing and coverage problems, the
probability of killing the point target given by the noncentral chi-squared distribution.
References
[R208], [R209]
Examples
Draw values from the distribution and plot the histogram
Draw values from a noncentral chisquare with very small noncentrality, and compare to a chisquare.
>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, .0000001, 100000),
... bins=np.arange(0., 25, .1), normed=True)
>>> values2 = plt.hist(np.random.chisquare(3, 100000),
... bins=np.arange(0., 25, .1), normed=True)
>>> plt.plot(values[1][0:-1], values[0]-values2[0], ob)
>>> plt.show()
>>> plt.figure()
>>> values = plt.hist(np.random.noncentral_chisquare(3, 20, 100000),
... bins=200, normed=True)
>>> plt.show()
0.05
0.04
0.03
0.02
0.01
0.00
0 10 20 30 40 50 60 70 80
0.25
0.20
0.15
0.10
0.05
0.00
0 5 10 15 20 25
0.05
0.04
0.03
0.02
0.01
0.00
0 10 20 30 40 50 60 70 80 90
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : scalar or ndarray
Drawn samples.
Notes
When calculating the power of an experiment (power = probability of rejecting the null hypothesis when
a specific alternative is true) the non-central F statistic becomes important. When the null hypothesis is
true, the F statistic follows a central F distribution. When the null hypothesis is not true, then it follows a
non-central F statistic.
References
Weisstein, Eric W. Noncentral F-Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/NoncentralF-Distribution.html
Wikipedia, Noncentral F distribution, http://en.wikipedia.org/wiki/Noncentral_F-distribution
Examples
In a study, testing for a specific alternative to the null hypothesis requires use of the Noncentral F distribu-
tion. We need to calculate the area in the tail of the distribution that exceeds the value of the F distribution
for the null hypothesis. Well plot the two probability distributions for comparison.
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
See Also:
scipy.stats.distributions.norm
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gaussian distribution is
1 (x)2
p(x) = e 2 2 ,
2 2
where is the mean and the standard deviation. The square of the standard deviation, 2 , is called the
variance.
The function has its peak at the mean, and its spread increases with the standard deviation (the function
reaches 0.607 times its maximum at x+ and x [R211]). This implies that numpy.random.normal
is more likely to return samples lying close to the mean, rather than those far away.
References
[R210], [R211]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
0
0.4 0.3 0.2 0.1 0.0 0.1 0.2 0.3
pareto(a, size=None)
Draw samples from a Pareto distribution with specified shape.
This is a simplified version of the Generalized Pareto distribution (available in SciPy), with the scale set to
one and the location set to zero. Most authors default the location to one.
The Pareto distribution must be greater than zero, and is unbounded above. It is also known as the 80-20
rule. In this distribution, 80 percent of the weights are in the lowest 20 percent of the range, while the
other 20 percent fill the remaining 80 percent of the range.
Parameters
shape : float, > 0.
Shape of the distribution.
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
See Also:
scipy.stats.distributions.genpareto.pdf
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Pareto distribution is
ama
p(x) =
xa+1
References
[R212], [R213], [R214], [R215]
Examples
Draw samples from the distribution:
Display the histogram of the samples, along with the probability density function:
2.5
2.0
1.5
1.0
0.5
0.0
0 2 4 6 8 10 12 14 16 18
permutation(x)
Randomly permute a sequence, or return a permuted range.
Parameters
x : int or array_like
If x is an integer, randomly permute np.arange(x). If x is an array, make a copy and
shuffle the elements randomly.
Returns
out : ndarray
Permuted sequence or array range.
Examples
>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])
poisson(lam=1.0, size=None)
Draw samples from a Poisson distribution.
The Poisson distribution is the limit of the Binomial distribution for large N.
Parameters
lam : float
Expectation of interval, should be >= 0.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Notes
The Poisson distribution
k e
f (k; ) =
k!
For events with an expected separation the Poisson distribution f (k; ) describes the probability of k
events occurring within the observed interval .
References
[R216], [R217]
Examples
Draw samples from the distribution:
0.30
0.25
0.20
0.15
0.10
0.05
0.00
0 2 4 6 8 10 12 14 16 18
power(a, size=None)
Draws samples in [0, 1] from a power distribution with positive exponent a - 1.
Also known as the power function distribution.
Parameters
a : float
parameter, > 0
size : tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then
m * n * k samples are drawn.
Returns
samples : {ndarray, scalar}
The returned samples lie in [0, 1].
Raises
ValueError :
If a<1.
Notes
The probability density function is
The power function distribution is just the inverse of the Pareto distribution. It may also be seen as a special
case of the Beta distribution.
It is used, for example, in modeling the over-reporting of insurance claims.
References
[R218], [R219]
Examples
rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and propagate it with random samples from a uniform distribution over
[0, 1).
Parameters
d0, d1, ..., dn : int
Shape of the output.
Returns
out : ndarray, shape (d0, d1, ..., dn)
Random values.
See Also:
random
Notes
This is a convenience function. If you want an interface that takes a shape-tuple as the first argument, refer
to random.
Examples
>>> np.random.rand(3,2)
array([[ 0.14022471, 0.96360618], #random
[ 0.37601032, 0.25528411], #random
[ 0.49313049, 0.94909878]]) #random
random.random_integers
similar to randint, only for the closed interval [low, high], and 1 is the lowest value if high is omitted.
In particular, this other one is the one to use to generate uniformly distributed discrete non-integers.
Examples
random.standard_normal
Similar, but takes a tuple as its argument.
Notes
For random samples from N (, 2 ), use:
sigma * np.random.randn(...) + mu
Examples
>>> np.random.randn()
2.1923875335537315 #random
random.randint
Similar to random_integers, only for the half-open interval [low, high), and 0 is the lowest value if
high is omitted.
Notes
To sample from N evenly spaced floating-point numbers between a and b, use:
a + (b - a) * (np.random.random_integers(N) - 1) / (N - 1.)
Examples
>>> np.random.random_integers(5)
4
>>> type(np.random.random_integers(5))
<type int>
>>> np.random.random_integers(5, size=(3.,2.))
array([[5, 4],
[3, 3],
[4, 5]])
Choose five random numbers from the set of five evenly-spaced numbers between 0 and 2.5, inclusive (i.e.,
from the set 0, 5/8, 10/8, 15/8, 20/8):
Roll two six sided dice 1000 times and sum the results:
0.20
0.15
0.10
0.05
0.00
2 4 6 8 10 12
random_sample(size=None)
Return random floats in the half-open interval [0.0, 1.0).
Results are from the continuous uniform distribution over the stated interval. To sample U nif [a, b), b >
a multiply the output of random_sample by (b-a) and add a:
(b - a) * random_sample() + a
Parameters
size : int or tuple of ints, optional
Defines the shape of the returned array of random floats. If None (the default), returns
a single float.
Returns
out : float or ndarray of floats
Array of random floats of shape size (unless size=None, in which case a single float
is returned).
Examples
>>> np.random.random_sample()
0.47108547995356098
>>> type(np.random.random_sample())
<type float>
>>> np.random.random_sample((5,))
array([ 0.30220482, 0.86820401, 0.1654503 , 0.11659149, 0.54323428])
rayleigh(scale=1.0, size=None)
Draw samples from a Rayleigh distribution.
The and Weibull distributions are generalizations of the Rayleigh.
Parameters
scale : scalar
Scale, also equals the mode. Should be >= 0.
size : int or tuple of ints, optional
Shape of the output. Default is None, in which case a single value is returned.
Notes
The probability density function for the Rayleigh distribution is
x x2
P (x; scale) = e 2scale2
scale2
The Rayleigh distribution arises if the wind speed and wind direction are both gaussian variables, then
the vector wind velocity forms a Rayleigh distribution. The Rayleigh distribution is used to model the
expected output from wind turbines.
References
..[1] Brighton Webs Ltd., Rayleigh Distribution,
http://www.brighton-webs.co.uk/distributions/rayleigh.asp
..[2] Wikipedia, Rayleigh distribution
http://en.wikipedia.org/wiki/Rayleigh_distribution
Examples
Draw values from the distribution and plot the histogram
Wave heights tend to follow a Rayleigh distribution. If the mean wave height is 1 meter, what fraction of
waves are likely to be larger than 3 meters?
>>> meanvalue = 1
>>> modevalue = np.sqrt(2 / np.pi) * meanvalue
>>> s = np.random.rayleigh(modevalue, 1000000)
>>> 100.*sum(s>3)/1000000.
0.087300000000000003
seed(seed=None)
Seed the generator.
This method is called when RandomState is initialized. It can be called again to re-seed the generator. For
details, see RandomState.
Parameters
seed : int or array_like, optional
Seed for RandomState.
See Also:
RandomState
set_state(state)
Set the internal state of the generator from a tuple.
For use if one has reason to manually (re-)set the internal state of the Mersenne Twister[R220] pseudo-
random number generating algorithm.
Parameters
state : tuple(str, ndarray of 624 uints, int, int, float)
The state tuple has the following items:
1. the string MT19937, specifying the Mersenne Twister algorithm.
2. a 1-D array of 624 unsigned integers keys.
3. an integer pos.
4. an integer has_gauss.
5. a float cached_gaussian.
Returns
out : None
Returns None on success.
See Also:
get_state
Notes
set_state and get_state are not needed to work with any of the random distributions in NumPy. If the
internal state is manually altered, the user should know exactly what he/she is doing.
For backwards compatibility, the form (str, array of 624 uints, int) is also accepted although it is missing
some information about the cached Gaussian value: state = (MT19937, keys, pos).
References
[R220]
shuffle(x)
Modify a sequence in-place by shuffling its contents.
standard_cauchy(size=None)
Standard Cauchy distribution with mode = 0.
Also known as the Lorentz distribution.
Parameters
size : int or tuple of ints
Shape of the output.
Returns
samples : ndarray or scalar
The drawn samples.
Notes
The probability density function for the full Cauchy distribution is
1
P (x; x0 , ) =
1 + ( xx
0 2
)
References
..[1] NIST/SEMATECH e-Handbook of Statistical Methods, Cauchy
Distribution, http://www.itl.nist.gov/div898/handbook/eda/section3/eda3663.htm
..[2] Weisstein, Eric W. Cauchy Distribution. From MathWorldA
Wolfram Web Resource. http://mathworld.wolfram.com/CauchyDistribution.html
..[3] Wikipedia, Cauchy distribution
http://en.wikipedia.org/wiki/Cauchy_distribution
Examples
Draw samples and plot the distribution:
>>> s = np.random.standard_cauchy(1000000)
>>> s = s[(s>-25) & (s<25)] # truncate distribution so it plots well
>>> plt.hist(s, bins=100)
>>> plt.show()
standard_exponential(size=None)
Draw samples from the standard exponential distribution.
standard_exponential is identical to the exponential distribution with a scale parameter of 1.
Parameters
size : int or tuple of ints
Shape of the output.
Returns
out : float or ndarray
Drawn samples.
Examples
Output a 3x8000 array:
standard_gamma(shape, size=None)
Draw samples from a Standard Gamma distribution.
Samples are drawn from a Gamma distribution with specified parameters, shape (sometimes designated
k) and scale=1.
Parameters
shape : float
Parameter, should be > 0.
size : int or tuple of ints
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : ndarray or scalar
The drawn samples.
See Also:
scipy.stats.distributions.gamma
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Gamma distribution is
ex/
p(x) = xk1 ,
k (k)
where k is the shape and the scale, and is the Gamma function.
The Gamma distribution is often used to model the times to failure of electronic components, and arises
naturally in processes for which the waiting times between Poisson distributed events are relevant.
References
[R221], [R222]
Examples
standard_normal(size=None)
Returns samples from a Standard Normal distribution (mean=0, stdev=1).
Parameters
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
Returns
out : float or ndarray
Drawn samples.
Examples
>>> s = np.random.standard_normal(8000)
>>> s
array([ 0.6888893 , 0.78096262, -0.89086505, ..., 0.49876311, #random
-0.38672696, -0.4685006 ]) #random
>>> s.shape
(8000,)
>>> s = np.random.standard_normal(size=(3, 4, 2))
>>> s.shape
(3, 4, 2)
standard_t(df, size=None)
Standard Students t distribution with df degrees of freedom.
A special case of the hyperbolic distribution. As df gets large, the result resembles that of the standard
normal distribution (standard_normal).
Parameters
df : int
Degrees of freedom, should be > 0.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
Returns
samples : ndarray or scalar
Drawn samples.
Notes
The probability density function for the t distribution is
The t test is based on an assumption that the data come from a Normal distribution. The t test provides a
way to test whether the sample mean (that is the mean calculated from the data) is a good estimate of the
true mean.
The derivation of the t-distribution was forst published in 1908 by William Gisset while working for the
Guinness Brewery in Dublin. Due to proprietary issues, he had to publish under a pseudonym, and so he
used the name Student.
References
[R223], [R224]
Examples
tomaxint(size=None)
Uniformly sample discrete random integers x such that 0 <= x <= sys.maxint.
Parameters
size : tuple of ints, int, optional
Shape of output. If the given size is, for example, (m,n,k), m*n*k samples are generated.
If no shape is specified, a single sample is returned.
Returns
out : ndarray
Drawn samples, with shape size.
See Also:
randint
Uniform sampling over a given half-open interval of integers.
random_integers
Uniform sampling over a given closed interval of integers.
Notes
The probability density function for the Triangular distribution is
2(xl)
(rl)(ml) for l x m,
2(mx)
P (x; l, m, r) = (rl)(rm) for m x r,
0 otherwise.
The triangular distribution is often used in ill-defined problems where the underlying distribution is not
known, but some knowledge of the limits and mode exists. Often it is used in simulations.
References
..[1] Wikipedia, Triangular distribution
http://en.wikipedia.org/wiki/Triangular_distribution
Examples
Draw values from the distribution and plot the histogram:
0.20
0.15
0.10
0.05
0.00
4 2 0 2 4 6 8
randint
Discrete uniform distribution, yielding integers.
random_integers
Discrete uniform distribution over the closed interval [low, high].
random_sample
Floats uniformly distributed over [0, 1).
random
Alias for random_sample.
rand
Convenience function that accepts dimensions as input, e.g., rand(2,2) would generate a 2-by-2
array of floats, uniformly distributed over [0, 1).
Notes
The probability density function of the uniform distribution is
1
p(x) =
ba
Examples
Draw samples from the distribution:
>>> s = np.random.uniform(-1,0,1000)
Display the histogram of the samples, along with the probability density function:
1.2
1.0
0.8
0.6
0.4
0.2
0.0
1.0 0.8 0.6 0.4 0.2 0.0
scipy.stats.distributions.vonmises
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the von Mises distribution is
ecos(x)
p(x) = ,
2I0 ()
where is the mode and the dispersion, and I0 () is the modified Bessel function of order 0.
The von Mises, named for Richard Edler von Mises, born in Austria-Hungary, in what is now the Ukraine.
He fled to the United States in 1939 and became a professor at Harvard. He worked in probability theory,
aerodynamics, fluid mechanics, and philosophy of science.
References
[R225], [R226], [R227]
Examples
wald(mean, scale, size=None)
Draw samples from a Wald, or Inverse Gaussian, distribution.
As the scale approaches infinity, the distribution becomes more like a Gaussian.
Some references claim that the Wald is an Inverse Gaussian with mean=1, but this is by no means universal.
The Inverse Gaussian distribution was first studied in relationship to Brownian motion. In 1956 M.C.K.
Tweedie used the name Inverse Gaussian because there is an inverse relationship between the time to cover
a unit distance and distance covered in unit time.
Parameters
mean : scalar
Distribution mean, should be > 0.
scale : scalar
Scale parameter, should be >= 0.
size : int or tuple of ints, optional
Output shape. Default is None, in which case a single value is returned.
Returns
samples : ndarray or scalar
Drawn sample, all greater than zero.
Notes
The probability density function for the Wald distribution is
r
scale scale(xmean)2
As noted above the Inverse Gaussian distribution first arise from attempts to model Brownian Motion. It
is also a competitor to the Weibull for use in reliability modeling and modeling stock returns and interest
rate processes.
References
..[1] Brighton Webs Ltd., Wald Distribution,
http://www.brighton-webs.co.uk/distributions/wald.asp
..[2] Chhikara, Raj S., and Folks, J. Leroy, The Inverse Gaussian
Distribution: Theory : Methodology, and Applications, CRC Press, 1988.
..[3] Wikipedia, Wald distribution
http://en.wikipedia.org/wiki/Wald_distribution
Examples
Draw values from the distribution and plot the histogram:
0.45
0.40
0.35
0.30
0.25
0.20
0.15
0.10
0.05
0.00
0 10 20 30 40 50 60 70 80
weibull(a, size=None)
Weibull distribution.
Draw samples from a 1-parameter Weibull distribution with the given shape parameter.
X = (ln(U ))1/a
scipy.stats.distributions.weibull
probability density function, distribution or cumulative density function, etc.
gumbel, scipy.stats.distributions.genextreme
Notes
The probability density for the Weibull distribution is
a x a1 (x/)a
p(x) = ( ) e ,
References
[R228], [R229], [R230]
Examples
Draw samples from the distribution:
>>> a = 5. # shape
>>> s = np.random.weibull(a, 1000)
Display the histogram of the samples, along with the probability density function:
250
200
150
100
50
0
0.0 0.5 1.0 1.5 2.0
zipf(a, size=None)
Draw samples from a Zipf distribution.
Samples are drawn from a Zipf distribution with specified parameter (a), where a > 1.
The zipf distribution (also known as the zeta distribution) is a continuous probability distribution that
satisfies Zipfs law, where the frequency of an item is inversely proportional to its rank in a frequency
table.
Parameters
a : float
parameter, > 1.
size : {tuple, int}
Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are
drawn.
Returns
samples : {ndarray, scalar}
The returned samples are greater than or equal to one.
See Also:
scipy.stats.distributions.zipf
probability density function, distribution or cumulative density function, etc.
Notes
The probability density for the Zipf distribution is
xa
p(x) = ,
(a)
References
[R231], [R232], [R233], [R234]
Examples
seed(seed=None)
Seed the generator.
This method is called when RandomState is initialized. It can be called again to re-seed the generator. For
details, see RandomState.
Parameters
seed : int or array_like, optional
Seed for RandomState.
See Also:
RandomState
get_state()
Return a tuple representing the internal state of the generator.
For more details, see set_state.
Returns
out : tuple(str, ndarray of 624 uints, int, int, float)
The returned tuple has the following items:
1. the string MT19937.
2. a 1-D array of 624 unsigned integer keys.
3. an integer pos.
4. an integer has_gauss.
5. a float cached_gaussian.
See Also:
set_state
Notes
set_state and get_state are not needed to work with any of the random distributions in NumPy. If the internal
state is manually altered, the user should know exactly what he/she is doing.
set_state(state)
Set the internal state of the generator from a tuple.
For use if one has reason to manually (re-)set the internal state of the Mersenne Twister[R252] pseudo-random
number generating algorithm.
Parameters
state : tuple(str, ndarray of 624 uints, int, int, float)
The state tuple has the following items:
1. the string MT19937, specifying the Mersenne Twister algorithm.
2. a 1-D array of 624 unsigned integers keys.
3. an integer pos.
4. an integer has_gauss.
5. a float cached_gaussian.
Returns
out : None
Returns None on success.
See Also:
get_state
Notes
set_state and get_state are not needed to work with any of the random distributions in NumPy. If the internal
state is manually altered, the user should know exactly what he/she is doing.
For backwards compatibility, the form (str, array of 624 uints, int) is also accepted although it is missing some
information about the cached Gaussian value: state = (MT19937, keys, pos).
References
[R252]
3.9.1 Sorting
ndarray.sort
Method to sort an array in-place.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in a sorted array.
Notes
The various sorting algorithms are characterized by their average speed, worst case performance, work space
size, and whether they are stable. A stable sort keeps items with the same key in the same relative order. The
three available algorithms have the following properties:
kind speed worst case work space stable
quicksort 1 O(n^2) 0 no
mergesort 2 O(n*log(n)) ~n/2 yes
heapsort 3 O(n*log(n)) 0 no
All the sort algorithms make temporary copies of the data when sorting along any but the last axis. Consequently,
sorting along the last axis is faster and uses less space than sorting along any other axis.
The sort order for complex numbers is lexicographic. If both the real and imaginary parts are non-nan then the
order is determined by the real parts except when they are equal, in which case the order is determined by the
imaginary parts.
Previous to numpy 1.4.0 sorting real and complex arrays containing nan values led to undefined behaviour. In
numpy versions >= 1.4.0 nan values are sorted to the end. The extended sort order is:
Real: [R, nan]
Complex: [R + Rj, R + nanj, nan + Rj, nan + nanj]
where R is a non-nan real value. Complex values with the same nan placements are sorted according to the
non-nan part if it exists. Non-nan values are sorted as before.
Examples
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a) # sort along the last axis
array([[1, 4],
[1, 3]])
>>> np.sort(a, axis=None) # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0) # sort along the first axis
array([[1, 1],
[3, 4]])
Use the order keyword to specify a field to use when sorting a structured array:
lexsort(keys, axis=-1)
Perform an indirect sort using a sequence of keys.
Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of
integer indices that describes the sort order by multiple columns. The last key in the sequence is used for the
primary sort order, the second-to-last key for the secondary sort order, and so on. The keys argument must be
a sequence of objects that can be converted to arrays of the same shape. If a 2D array is provided for the keys
argument, its rows are interpreted as the sorting keys and sorting is according to the last row, second last row
etc.
Parameters
keys : (k,N) array or tuple containing k (N,)-shaped sequences
The k different columns to be sorted. The last column (or row if keys is a 2D array) is
the primary sort key.
axis : int, optional
Axis to be indirectly sorted. By default, sort over the last axis.
Returns
indices : (N,) ndarray of ints
Array of indices that sort the keys along the specified axis.
See Also:
argsort
Indirect sort.
ndarray.sort
In-place sort.
sort
Return a sorted copy of an array.
Examples
Sort names: first by surname, then by name.
Note that sorting is first according to the elements of a. Secondary sorting is according to the elements of b.
A normal argsort would have yielded:
sort
Describes sorting algorithms used.
lexsort
Indirect stable sort with multiple keys.
ndarray.sort
Inplace sort.
Notes
See sort for notes on the different sorting algorithms.
As of NumPy 1.4.0 argsort works with real/complex arrays containing nan values. The enhanced sort order is
documented in sort.
Examples
One dimensional array:
Two-dimensional array:
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
msort(a)
Return a copy of an array sorted along the first axis.
Parameters
a : array_like
Array to be sorted.
Returns
sorted_array : ndarray
Array of the same type and shape as a.
See Also:
sort
Notes
np.msort(a) is equivalent to np.sort(a, axis=0).
sort_complex(a)
Sort a complex array using the real part first, then the imaginary part.
Parameters
a : array_like
Input array
Returns
out : complex ndarray
Always returns a sorted complex array.
Examples
3.9.2 Searching
Notes
In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are
returned.
Examples
>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0)
array([1, 1, 1])
>>> np.argmax(a, axis=1)
array([2, 2])
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) # Only the first occurrence is returned.
1
nanargmax(a, axis=None)
Return indices of the maximum values over an axis, ignoring NaNs.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
index_array : ndarray
An array of indices or a single index value.
See Also:
argmax, nanargmin
Examples
argmin(a, axis=None)
Return the indices of the minimum values along an axis.
See Also:
argmax
Similar function. Please refer to numpy.argmax for detailed documentation.
nanargmin(a, axis=None)
Return indices of the minimum values over an axis, ignoring NaNs.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default flattened input is used.
Returns
index_array : ndarray
An array of indices or a single index value.
See Also:
argmin, nanargmax
Examples
argwhere(a)
Find the indices of array elements that are non-zero, grouped by element.
Parameters
a : array_like
Input data.
Returns
index_array : ndarray
Indices of elements that are non-zero. Indices are grouped by element.
See Also:
where, nonzero
Notes
np.argwhere(a) is the same as np.transpose(np.nonzero(a)).
The output of argwhere is not suitable for indexing arrays. For this purpose use where(a) instead.
Examples
>>> x = np.arange(6).reshape(2,3)
>>> x
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argwhere(x>1)
array([[0, 2],
[1, 0],
[1, 1],
[1, 2]])
nonzero(a)
Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[nonzero(a)]
transpose(nonzero(a))
The result of this is always a 2-D array, with a row for each non-zero element.
Parameters
a : array_like
Input array.
Returns
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also:
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
>>> x = np.eye(3)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> np.nonzero(x)
(array([0, 1, 2]), array([0, 1, 2]))
>>> x[np.nonzero(x)]
array([ 1., 1., 1.])
>>> np.transpose(np.nonzero(x))
array([[0, 0],
[1, 1],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, np.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
array([[False, False, False],
[ True, True, True],
[ True, True, True]], dtype=bool)
>>> np.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
flatnonzero(a)
Return indices that are non-zero in the flattened version of a.
This is equivalent to a.ravel().nonzero()[0].
Parameters
a : ndarray
Input array.
Returns
res : ndarray
Output array, containing the indices of the elements of a.ravel() that are non-zero.
See Also:
nonzero
Return the indices of the non-zero elements of the input array.
ravel
Return a 1-D array containing the elements of the input array.
Examples
>>> x = np.arange(-2, 3)
>>> x
array([-2, -1, 0, 1, 2])
>>> np.flatnonzero(x)
array([0, 1, 3, 4])
Use the indices of the non-zero elements as an index array to extract these elements:
>>> x.ravel()[np.flatnonzero(x)]
array([-2, -1, 1, 2])
Values from which to choose. x and y need to have the same shape as condition.
Returns
out : ndarray or tuple of ndarrays
If both x and y are specified, the output array contains elements of x where condition is
True, and elements from y elsewhere.
If only condition is given, return the tuple condition.nonzero(), the indices
where condition is True.
See Also:
nonzero, choose
Notes
If x and y are given and input arrays are 1-D, where is equivalent to:
Examples
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 3.0 )] # Note: result is 1D.
array([ 4., 5., 6., 7., 8.])
>>> np.where(x < 5, x, -1) # Note: broadcasting.
array([[ 0., 1., 2.],
[ 3., 4., -1.],
[-1., -1., -1.]])
searchsorted(a, v, side=left)
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array a such that, if the corresponding elements in v were inserted before the
indices, the order of a would be preserved.
Parameters
a : 1-D array_like
Input array, sorted in ascending order.
v : array_like
Values to insert into a.
side : {left, right}, optional
If left, the index of the first suitable location found is given. If right, return the last
such index. If there is no suitable index, return either 0 or N (where N is the length of
a).
Returns
indices : array of ints
Array of insertion points with the same shape as v.
See Also:
sort
Return a sorted copy of an array.
histogram
Produce histogram from 1-D data.
Notes
Binary search is used to find the required insertion points.
As of Numpy 1.4.0 searchsorted works with real/complex arrays containing nan values. The enhanced sort
order is documented in sort.
Examples
>>> np.searchsorted([1,2,3,4,5], 3)
2
>>> np.searchsorted([1,2,3,4,5], 3, side=right)
3
>>> np.searchsorted([1,2,3,4,5], [-10, 10, 2, 3])
array([0, 5, 1, 2])
extract(condition, arr)
Return the elements of an array that satisfy some condition.
This is equivalent to np.compress(ravel(condition), ravel(arr)). If condition is boolean
np.extract is equivalent to arr[condition].
Parameters
condition : array_like
An array whose nonzero or True entries indicate the elements of arr to extract.
arr : array_like
Input array of the same size as condition.
See Also:
take, put, putmask, compress
Examples
If condition is boolean:
>>> arr[condition]
array([0, 3, 6, 9])
all(a[, axis, out]) Test whether all array elements along a given axis evaluate to True.
any(a[, axis, out]) Test whether any array element along a given axis evaluates to True.
all(a, axis=None, out=None)
Test whether all array elements along a given axis evaluate to True.
Parameters
a : array_like
Input array or object that can be converted to an array.
axis : int, optional
Axis along which a logical AND is performed. The default (axis = None) is to perform
a logical AND over a flattened input array. axis may be negative, in which case it counts
from the last to the first axis.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output and the type is preserved. See doc.ufuncs (Section Output arguments)
for more details.
Returns
all : ndarray, bool
A new boolean or array is returned unless out is specified, in which case a reference to
out is returned.
See Also:
ndarray.all
equivalent method
any
Test whether any array element along a given axis evaluates to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.
Examples
>>> np.all([[True,False],[True,True]])
False
>>> o=np.array([False])
>>> z=np.all([-1, 4, 5], out=o)
>>> id(z), id(o), z
(28293632, 28293632, array([ True], dtype=bool))
ndarray.any
equivalent method
all
Test whether all array elements along a given axis evaluate to True.
Notes
Not a Number (NaN), positive infinity and negative infinity evaluate to True because these are not equal to zero.
Examples
>>> np.any(np.nan)
True
>>> o=np.array([False])
>>> z=np.any([-1, 4, 5], out=o)
>>> z, o
(array([ True], dtype=bool), array([ True], dtype=bool))
>>> # Check now that z is a reference to o
>>> z is o
True
>>> id(z), id(o) # identity of z and o
(191614240, 191614240)
isfinite() Test element-wise for finite-ness (not infinity or not Not a Number).
isinf() Test element-wise for positive or negative infinity, return result as bool array.
isnan() Test element-wise for Not a Number (NaN), return result as a bool array.
isneginf(x[, y]) Test element-wise for negative infinity, return result as bool array.
isposinf(x[, y]) Test element-wise for positive infinity, return result as bool array.
isfinite
Test element-wise for finite-ness (not infinity or not Not a Number).
The result is returned as a boolean array.
Parameters
x : array_like
Input values.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
y : ndarray, bool
For scalar input, the result is a new boolean with value True if the input is finite; oth-
erwise the value is False (input is either positive infinity, negative infinity or Not a
Number).
For array input, the result is a boolean array with the same dimensions as the input and
the values are True if the corresponding element of the input is finite; otherwise the
values are False (element is either positive infinity, negative infinity or Not a Number).
See Also:
isinf, isneginf, isposinf, isnan
Notes
Not a Number, positive infinity and negative infinity are considered to be non-finite.
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a
Number is not equivalent to infinity. Also that positive infinity is not equivalent to negative infinity. But infinity
is equivalent to positive infinity. Errors result if the second argument is also supplied when x is a scalar input,
or if first and second arguments have different shapes.
Examples
>>> np.isfinite(1)
True
>>> np.isfinite(0)
True
>>> np.isfinite(np.nan)
False
>>> np.isfinite(np.inf)
False
>>> np.isfinite(np.NINF)
False
>>> np.isfinite([np.log(-1.),1.,np.log(0)])
array([False, True, False], dtype=bool)
isinf
Test element-wise for positive or negative infinity, return result as bool array.
Parameters
x : array_like
Input values
y : array_like, optional
An array with the same shape as x to store the result.
Returns
y : {ndarray, bool}
For scalar input, the result is a new boolean with value True if the input is positive or
negative infinity; otherwise the value is False.
For array input, the result is a boolean array with the same dimensions as the input
and the values are True if the corresponding element of the input is positive or negative
infinity; otherwise the values are False. If a second argument is supplied the result is
stored there. If the type of that array is a numeric type the result is represented as zeros
and ones, if the type is boolean then as False and True. The return value y is then a
reference to that array.
See Also:
isneginf, isposinf, isnan, isfinite
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
Errors result if second argument is also supplied with scalar input or if first and second arguments have different
shapes.
Examples
>>> np.isinf(np.inf)
True
>>> np.isinf(np.nan)
False
>>> np.isinf(np.NINF)
True
>>> np.isinf([np.inf, -np.inf, 1.0, np.nan])
array([ True, True, False, False], dtype=bool)
isnan
Test element-wise for Not a Number (NaN), return result as a bool array.
Parameters
x : array_like
Input array.
Returns
y : {ndarray, bool}
For scalar input, the result is a new boolean with value True if the input is NaN; other-
wise the value is False.
For array input, the result is a boolean array with the same dimensions as the input
and the values are True if the corresponding element of the input is NaN; otherwise the
values are False.
See Also:
isinf, isneginf, isposinf, isfinite
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a
Number is not equivalent to infinity.
Examples
>>> np.isnan(np.nan)
True
>>> np.isnan(np.inf)
False
>>> np.isnan([np.log(-1.),1.,np.log(0)])
array([ True, False, False], dtype=bool)
isneginf(x, y=None)
Test element-wise for negative infinity, return result as bool array.
Parameters
x : array_like
The input array.
y : array_like, optional
A boolean array with the same shape and type as x to store the result.
Returns
y : ndarray
A boolean array with the same dimensions as the input. If second argument is not sup-
plied then a numpy boolean array is returned with values True where the corresponding
element of the input is negative infinity and values False where the element of the input
is not negative infinity.
If a second argument is supplied the result is stored there. If the type of that array is a
numeric type the result is represented as zeros and ones, if the type is boolean then as
False and True. The return value y is then a reference to that array.
See Also:
isinf, isposinf, isnan, isfinite
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
Errors result if the second argument is also supplied when x is a scalar input, or if first and second arguments
have different shapes.
Examples
>>> np.isneginf(np.NINF)
array(True, dtype=bool)
>>> np.isneginf(np.inf)
array(False, dtype=bool)
>>> np.isneginf(np.PINF)
array(False, dtype=bool)
>>> np.isneginf([-np.inf, 0., np.inf])
array([ True, False, False], dtype=bool)
isposinf(x, y=None)
Test element-wise for positive infinity, return result as bool array.
Parameters
x : array_like
The input array.
y : array_like, optional
A boolean array with the same shape as x to store the result.
Returns
y : ndarray
A boolean array with the same dimensions as the input. If second argument is not
supplied then a boolean array is returned with values True where the corresponding
element of the input is positive infinity and values False where the element of the input
is not positive infinity.
If a second argument is supplied the result is stored there. If the type of that array is a
numeric type the result is represented as zeros and ones, if the type is boolean then as
False and True. The return value y is then a reference to that array.
See Also:
isinf, isneginf, isfinite, isnan
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754).
Errors result if the second argument is also supplied when x is a scalar input, or if first and second arguments
have different shapes.
Examples
>>> np.isposinf(np.PINF)
array(True, dtype=bool)
>>> np.isposinf(np.inf)
array(True, dtype=bool)
>>> np.isposinf(np.NINF)
array(False, dtype=bool)
>>> np.isposinf([-np.inf, 0., np.inf])
array([False, False, True], dtype=bool)
iscomplex(x)
Returns a bool array, where True if input element is complex.
What is tested is whether the input has a non-zero imaginary part, not if the input type is complex.
Parameters
x : array_like
Input array.
Returns
out : ndarray of bools
Output array.
See Also:
isreal
iscomplexobj
Return True if x is a complex type or an array of complex numbers.
Examples
iscomplexobj(x)
Return True if x is a complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero,
iscomplexobj evaluates to True if the data type is complex.
Parameters
x : any
The input can be of any type and shape.
Returns
y : bool
The return value, True if x is of a complex type.
See Also:
isrealobj, iscomplex
Examples
>>> np.iscomplexobj(1)
False
>>> np.iscomplexobj(1+0j)
True
>>> np.iscomplexobj([3, 1+0j, True])
True
isfortran(a)
Returns True if array is arranged in Fortran-order in memory and dimension > 1.
Parameters
a : ndarray
Input array.
Examples
np.array allows to specify whether the array is written in C-contiguous order (last index varies the fastest), or
FORTRAN-contiguous order in memory (first index varies the fastest).
isreal(x)
Returns a bool array, where True if input element is real.
If element has complex type with zero complex part, the return value for that element is True.
Parameters
x : array_like
Input array.
Returns
out : ndarray, bool
Boolean array of same shape as x.
See Also:
iscomplex
isrealobj
Return True if x is not a complex type.
Examples
isrealobj(x)
Return True if x is a not complex type or an array of complex numbers.
The type of the input is checked, not the value. So even if the input has an imaginary part equal to zero, isrealobj
evaluates to False if the data type is complex.
Parameters
x : any
The input can be of any type and shape.
Returns
y : bool
The return value, False if x is of a complex type.
See Also:
iscomplexobj, isreal
Examples
>>> np.isrealobj(1)
True
>>> np.isrealobj(1+0j)
False
>>> np.isrealobj([3, 1+0j, True])
False
isscalar(num)
Returns True if the type of num is a scalar type.
Parameters
num : any
Input argument, can be of any type and shape.
Returns
val : bool
True if num is a scalar type, False if it is not.
Examples
>>> np.isscalar(3.1)
True
>>> np.isscalar([3.1])
False
>>> np.isscalar(False)
True
Examples
>>> x = np.arange(5)
>>> np.logical_and(x>1, x<4)
array([False, False, True, True, False], dtype=bool)
logical_or
Compute the truth value of x1 OR x2 elementwise.
Parameters
x1, x2 : array_like
Logical OR is applied to the elements of x1 and x2. They have to be of the same shape.
Returns
y : {ndarray, bool}
Boolean result with the same shape as x1 and x2 of the logical OR operation on elements
of x1 and x2.
See Also:
logical_and, logical_not, logical_xor, bitwise_or
Examples
>>> x = np.arange(5)
>>> np.logical_or(x < 1, x > 3)
array([ True, False, False, False, True], dtype=bool)
logical_not
Compute the truth value of NOT x elementwise.
Parameters
x : array_like
Logical NOT is applied to the elements of x.
Returns
y : {ndarray, bool}
Boolean result with the same shape as x of the NOT operation on elements of x.
See Also:
logical_and, logical_or, logical_xor
Examples
>>> np.logical_not(3)
False
>>> np.logical_not([True, False, 0, 1])
array([False, True, True, False], dtype=bool)
>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False, True, True], dtype=bool)
logical_xor
Compute the truth value of x1 XOR x2 elementwise.
Parameters
x1, x2 : array_like
Logical XOR is applied to the elements of x1 and x2. They have to be of the same
shape.
Returns
y : {ndarray, bool}
Boolean result with the same shape as x1 and x2 of the logical XOR operation on ele-
ments of x1 and x2.
See Also:
logical_and, logical_or, logical_not, bitwise_xor
Examples
>>> x = np.arange(5)
>>> np.logical_xor(x < 1, x > 3)
array([ True, False, False, False, True], dtype=bool)
3.10.5 Comparison
allclose(a, b[, rtol, atol]) Returns True if two arrays are element-wise equal within a tolerance.
array_equal(a1, a2) True if two arrays have the same shape and elements, False otherwise.
array_equiv(a1, a2) Returns True if input arrays are shape consistent and all elements equal.
allclose(a, b, rtol=1.0000000000000001e-05, atol=1e-08)
Returns True if two arrays are element-wise equal within a tolerance.
The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the
absolute difference atol are added together to compare against the absolute difference between a and b.
Parameters
a, b : array_like
Input arrays to compare.
rtol : float
The relative tolerance parameter (see Notes).
atol : float
The absolute tolerance parameter (see Notes).
Returns
y : bool
Returns True if the two arrays are equal within the given tolerance; False otherwise. If
either array contains NaN, then False is returned.
See Also:
all, any, alltrue, sometrue
Notes
If the following equation is element-wise True, then allclose returns True.
absolute(a - b) <= (atol + rtol * absolute(b))
The above equation is not symmetric in a and b, so that allclose(a, b) might be different from allclose(b, a) in
some rare cases.
Examples
array_equal(a1, a2)
True if two arrays have the same shape and elements, False otherwise.
Parameters
a1, a2 : array_like
Input arrays.
Returns
b : bool
Returns True if the arrays are equal.
See Also:
allclose
Returns True if two arrays are element-wise equal within a tolerance.
array_equiv
Returns True if input arrays are shape consistent and all elements equal.
Examples
array_equiv(a1, a2)
Returns True if input arrays are shape consistent and all elements equal.
Shape consistent means they are either the same shape, or one input array can be broadcasted to create the same
shape as the other one.
Parameters
a1, a2 : array_like
Input arrays.
Returns
out : bool
True if equivalent, False otherwise.
Examples
Examples
>>> np.greater([4,2],[2,2])
array([ True, False], dtype=bool)
>>> a = np.array([4,2])
>>> b = np.array([2,2])
>>> a > b
array([ True, False], dtype=bool)
greater_equal
Return (x1 >= x2) element-wise.
Parameters
x1, x2 : array_like
Input arrays.
Returns
out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also:
greater, less, less_equal, equal, not_equal
Examples
less
Return (x1 < x2) element-wise.
Parameters
x1, x2 : array_like
Input arrays.
Returns
Out : ndarray of bools
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also:
less_equal, greater, greater_equal, equal, not_equal
Examples
less_equal
Return (x1 <= x2) element-wise.
Parameters
x1, x2 : array_like
Input arrays.
Returns
Out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also:
less, greater_equal, greater, equal, not_equal
Examples
equal
Return (x1 == x2) element-wise.
Parameters
x1, x2 : array_like
Input arrays of the same shape.
Returns
out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also:
not_equal, greater_equal, less_equal, greater, less
Examples
What is compared are values, not types. So an int (1) and an array of length one can evaluate as True:
not_equal
Return (x1 != x2) element-wise.
Parameters
x1, x2 : array_like
Input arrays.
out : ndarray, optional
A placeholder the same shape as x1 to store the result. See doc.ufuncs (Section Output
arguments) for more details.
Returns
not_equal : ndarray bool, scalar bool
For each element in x1, x2, return True if x1 is not equal to x2 and False otherwise.
See Also:
equal, greater, greater_equal, less, less_equal
Examples
Parameters
x1, x2 : array_like
Only integer types are handled (including booleans).
Returns
out : array_like
Result.
See Also:
logical_and, bitwise_or, bitwise_xor
binary_repr
Return the binary representation of the input number as a string.
Examples
The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise AND
of 13 and 17 is therefore 000000001, or 1:
bitwise_or
Compute the bit-wise OR of two arrays element-wise.
Computes the bit-wise OR of the underlying binary representation of the integers in the input arrays. This ufunc
implements the C/Python operator |.
Parameters
x1, x2 : array_like
Only integer types are handled (including booleans).
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
out : array_like
Result.
See Also:
logical_or, bitwise_and, bitwise_xor
binary_repr
Return the binary representation of the input number as a string.
Examples
The number 13 has the binaray representation 00001101. Likewise, 16 is represented by 00010000. The
bit-wise OR of 13 and 16 is then 000111011, or 29:
>>> np.bitwise_or(32, 2)
34
>>> np.bitwise_or([33, 4], 1)
array([33, 5])
>>> np.bitwise_or([33, 4], [1, 2])
array([33, 6])
bitwise_xor
Compute the bit-wise XOR of two arrays element-wise.
Computes the bit-wise XOR of the underlying binary representation of the integers in the input arrays. This
ufunc implements the C/Python operator ^.
Parameters
x1, x2 : array_like
Only integer types are handled (including booleans).
Returns
out : array_like
Result.
See Also:
logical_xor, bitwise_and, bitwise_or
binary_repr
Return the binary representation of the input number as a string.
Examples
The number 13 is represented by 00001101. Likewise, 17 is represented by 00010001. The bit-wise XOR
of 13 and 17 is therefore 00011100, or 28:
>>> np.bitwise_xor(31, 5)
26
>>> np.bitwise_xor([31,3], 5)
array([26, 6])
invert
Compute bit-wise inversion, or bit-wise NOT, element-wise.
Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays. This
ufunc implements the C/Python operator ~.
For signed integer inputs, the twos complement is returned. In a twos-complement system negative numbers
are represented by the twos complement of the absolute value. This is the most common method of representing
signed integers on computers [R41]. A N-bit twos-complement system can represent every integer in the range
2N 1 to +2N 1 1.
Parameters
x1 : array_like
Only integer types are handled (including booleans).
Returns
out : array_like
Result.
See Also:
bitwise_and, bitwise_or, bitwise_xor, logical_not
binary_repr
Return the binary representation of the input number as a string.
Notes
bitwise_not is an alias for invert:
References
[R41]
Examples
Weve seen that 13 is represented by 00001101. The invert or bit-wise NOT of 13 is then:
When using signed integer types the result is the twos complement of the result for the unsigned type:
left_shift
Shift the bits of an integer to the left.
Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is
in binary format, this operation is equivalent to multiplying x1 by 2**x2.
Parameters
x1 : array_like of integer type
Input values.
x2 : array_like of integer type
Number of zeros to append to x1. Has to be non-negative.
Returns
out : array of integer type
Return x1 with bits shifted x2 times to the left.
See Also:
right_shift
Shift the bits of an integer to the right.
binary_repr
Return the binary representation of the input number as a string.
Examples
>>> np.binary_repr(5)
101
>>> np.left_shift(5, 2)
20
>>> np.binary_repr(20)
10100
right_shift
Shift the bits of an integer to the right.
Bits are shifted to the right by removing x2 bits at the right of x1. Since the internal representation of numbers
is in binary format, this operation is equivalent to dividing x1 by 2**x2.
Parameters
x1 : array_like, int
Input values.
x2 : array_like, int
Number of bits to remove at the right of x1.
Returns
out : ndarray, int
Return x1 with bits shifted x2 times to the right.
See Also:
left_shift
Shift the bits of an integer to the left.
binary_repr
Return the binary representation of the input number as a string.
Examples
>>> np.binary_repr(10)
1010
>>> np.right_shift(10, 1)
5
>>> np.binary_repr(5)
101
packbits(myarray[, axis]) Packs the elements of a binary-valued array into bits in a uint8 array.
unpackbits(myarray[, axis]) Unpacks elements of a uint8 array into a binary-valued output array.
packbits(myarray, axis=None)
Packs the elements of a binary-valued array into bits in a uint8 array.
The result is padded to full bytes by inserting zero bits at the end.
Parameters
myarray : array_like
An integer type array whose elements should be packed to bits.
axis : int, optional
The dimension over which bit-packing is done. None implies packing the flattened
array.
Returns
packed : ndarray
Array of type uint8 whose elements represent bits corresponding to the logical (0 or
nonzero) value of the input elements. The shape of packed has the same number of
dimensions as the input (unless axis is None, in which case the output is 1-D).
See Also:
unpackbits
Unpacks elements of a uint8 array into a binary-valued output array.
Examples
>>> a = np.array([[[1,0,1],
... [0,1,0]],
... [[1,1,0],
... [0,0,1]]])
>>> b = np.packbits(a, axis=-1)
>>> b
array([[[160],[64]],[[192],[32]]], dtype=uint8)
Note that in binary 160 = 1010 0000, 64 = 0100 0000, 192 = 1100 0000, and 32 = 0010 0000.
unpackbits(myarray, axis=None)
Unpacks elements of a uint8 array into a binary-valued output array.
Each element of myarray represents a bit-field that should be unpacked into a binary-valued output array. The
shape of the output array is either 1-D (if axis is None) or the same shape as the input array with unpacking done
along the axis specified.
Parameters
myarray : ndarray, uint8 type
Input array.
axis : int, optional
Unpacks along this axis.
Returns
unpacked : ndarray, uint8 type
The elements are binary-valued (0 or 1).
See Also:
packbits
Packs the elements of a binary-valued array into bits in a uint8 array.
Examples
binary_repr(num[, width]) Return the binary representation of the input number as a string.
binary_repr(num, width=None)
Return the binary representation of the input number as a string.
For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the twos
complement of the number is returned, with respect to that width.
In a twos-complement system negative numbers are represented by the twos complement of the absolute
value. This is the most common method of representing signed integers on computers [R23]. A N-bit twos-
complement system can represent every integer in the range 2N 1 to +2N 1 1.
Parameters
num : int
Only an integer decimal number can be used.
width : int, optional
The length of the returned string if num is positive, the length of the twos complement
if num is negative.
Returns
bin : str
Binary representation of num or twos complement of num.
See Also:
base_repr
Return a string representation of a number in the given base system.
Notes
binary_repr is equivalent to using base_repr with base 2, but about 25x faster.
References
[R23]
Examples
>>> np.binary_repr(3)
11
>>> np.binary_repr(-3)
-11
>>> np.binary_repr(3, width=4)
0011
The twos complement is returned when the input number is negative and width is specified:
3.12 Statistics
amin(a[, axis, out]) Return the minimum of an array or minimum along an axis.
amax(a[, axis, out]) Return the maximum of an array or maximum along an axis.
nanmax(a[, axis]) Return the maximum of an array or maximum along an axis ignoring any NaNs.
nanmin(a[, axis]) Return the minimum of an array or minimum along an axis ignoring any NaNs.
ptp(a[, axis, out]) Range of values (maximum - minimum) along an axis.
amin(a, axis=None, out=None)
Return the minimum of an array or minimum along an axis.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which to operate. By default a flattened input is used.
out : ndarray, optional
Alternative output array in which to place the result. Must be of the same shape and
buffer length as the expected output. See doc.ufuncs (Section Output arguments) for
more details.
Returns
amin : ndarray
A new array or a scalar array with the result.
See Also:
nanmin
nan values are ignored instead of being propagated
fmin
same behavior as the C99 fmin function
argmin
Return the indices of the minimum values.
Notes
NaN values are propagated, that is if at least one item is nan, the corresponding min value will be nan as well.
To ignore NaN values (matlab behavior), please use nanmin.
Examples
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amin(a) # Minimum of the flattened array
0
>>> np.amin(a, axis=0) # Minima along the first axis
array([0, 1])
>>> np.amin(a, axis=1) # Minima along the second axis
array([0, 2])
nanmax
nan values are ignored instead of being propagated
fmax
same behavior as the C99 fmax function
argmax
Indices of the maximum values.
Notes
NaN values are propagated, that is if at least one item is nan, the corresponding max value will be nan as well.
To ignore NaN values (matlab behavior), please use nanmax.
Examples
>>> a = np.arange(4).reshape((2,2))
>>> a
array([[0, 1],
[2, 3]])
>>> np.amax(a)
3
>>> np.amax(a, axis=0)
array([2, 3])
>>> np.amax(a, axis=1)
array([1, 3])
nanmax(a, axis=None)
Return the maximum of an array or maximum along an axis ignoring any NaNs.
Parameters
a : array_like
Array containing numbers whose maximum is desired. If a is not an array, a conversion
is attempted.
axis : int, optional
Axis along which the maximum is computed. The default is to compute the maximum
of the flattened array.
Returns
nanmax : ndarray
An array with the same shape as a, with the specified axis removed. If a is a 0-d array,
or if axis is None, a ndarray scalar is returned. The the same dtype as a is returned.
See Also:
numpy.amax
Maximum across array including any Not a Numbers.
numpy.nanmin
Minimum across array ignoring any Not a Numbers.
isnan
Shows which elements are Not a Number (NaN).
isfinite
Shows which elements are not: Not a Number, positive and negative infinity
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a
Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is
treated as a very small (i.e. negative) number.
If the input has a integer type, an integer type is returned unless the input contains NaNs and infinity.
Examples
nanmin(a, axis=None)
Return the minimum of an array or minimum along an axis ignoring any NaNs.
Parameters
a : array_like
Array containing numbers whose minimum is desired.
axis : int, optional
Axis along which the minimum is computed.The default is to compute the minimum of
the flattened array.
Returns
nanmin : ndarray
A new array or a scalar array with the result.
See Also:
numpy.amin
Minimum across array including any Not a Numbers.
numpy.nanmax
Maximum across array ignoring any Not a Numbers.
isnan
Shows which elements are Not a Number (NaN).
isfinite
Shows which elements are not: Not a Number, positive and negative infinity
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a
Number is not equivalent to infinity. Positive infinity is treated as a very large number and negative infinity is
treated as a very small (i.e. negative) number.
If the input has a integer type, an integer type is returned unless the input contains NaNs and infinity.
Examples
Examples
>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
[2, 3]])
average(a[, axis, weights, returned]) Compute the weighted average along the specified axis.
mean(a[, axis, dtype, out]) Compute the arithmetic mean along the specified axis.
median(a[, axis, out, overwrite_input]) Compute the median along the specified axis.
std(a[, axis, dtype, out, ddof]) Compute the standard deviation along the specified axis.
var(a[, axis, dtype, out, ddof]) Compute the variance along the specified axis.
average(a, axis=None, weights=None, returned=False)
Compute the weighted average along the specified axis.
Parameters
a : array_like
Array containing data to be averaged. If a is not an array, a conversion is attempted.
axis : int, optional
Axis along which to average a. If None, averaging is done over the flattened array.
weights : array_like, optional
An array of weights associated with the values in a. Each value in a contributes to the
average according to its associated weight. The weights array can either be 1-D (in
which case its length must be the size of a along the given axis) or of the same shape as
a. If weights=None, then all data in a are assumed to have a weight equal to one.
returned : bool, optional
Default is False. If True, the tuple (average, sum_of_weights) is returned, otherwise
only the average is returned. If weights=None, sum_of_weights is equivalent to the
number of elements over which the average is taken.
Returns
average, [sum_of_weights] : {array_type, double}
Return the average along the specified axis. When returned is True, return a tuple with
the average as the first element and the sum of the weights as the second element.
The return type is Float if a is of integer type, otherwise it is of the same type as a.
sum_of_weights is of the same type as average.
Raises
ZeroDivisionError :
When all weights along axis are zero. See numpy.ma.average for a version robust
to this type of error.
TypeError :
When the length of 1D weights is not the same as the shape of a along axis.
See Also:
mean
ma.average
average for masked arrays
Examples
>>> np.average(data)
2.5
>>> np.average(range(1,11), weights=range(10,0,-1))
4.0
average
Weighted average
Notes
The arithmetic mean is the sum of the elements along the axis divided by the number of elements.
Note that for floating-point input, the mean is computed using the same precision the input has. Depending on
the input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying
a higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
Notes
Given a vector V of length N, the median of V is the middle value of a sorted copy of V, V_sorted - i.e.,
V_sorted[(N-1)/2], when N is odd. When N is even, it is the average of the two middle values of
V_sorted.
Examples
Notes
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =
sqrt(mean(abs(x - x.mean())**2)).
The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however,
ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate
of the variance for normally distributed variables. The standard deviation computed in this function is the
square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard
deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real
and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input
data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-
accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed
for the flattened array by default, otherwise over the specified axis.
Parameters
a : array_like
Array containing numbers whose variance is desired. If a is not an array, a conversion
is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type the default is float32;
for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type is cast if necessary.
ddof : int, optional
Delta Degrees of Freedom: the divisor used in calculation is N - ddof, where N
represents the number of elements. By default ddof is zero.
Returns
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise a reference to the
output array is returned.
See Also:
std
Standard deviation
mean
Average
numpy.doc.ufuncs
Section Output arguments
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x -
x.mean())**2).
The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the
divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of
the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for
normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and
nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the
input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a
higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
3.12.3 Correlating
cov
Covariance matrix
convolve
Discrete, linear convolution of two one-dimensional sequences.
acorrelate
Discrete correlation following the usual signal processing definition for complex arrays, and without as-
suming that correlate(a, b) == correlate(b, a).
Notes
If old_behavior is False, this function computes the correlation as generally defined in signal processing texts:
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Examples
corrcoef
Normalized covariance matrix
Examples
Consider two variables, x0 and x1 , which correlate perfectly, but in opposite directions:
Note how x0 increases while x1 decreases. The covariance matrix shows this clearly:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
Note that element C0,1 , which shows the correlation between x0 and x1 , is negative.
Further, note how x and y are combined:
3.12.4 Histograms
Notes
All but the last (righthand-most) bin is half-open. In other words, if bins is:
[1, 2, 3, 4]
then the first bin is [1, 2) (including 1, but excluding 2) and the second [2, 3). The last bin, however, is
[3, 4], which includes 4.
Examples
>>> a = np.arange(5)
>>> hist, bin_edges = np.histogram(a, normed=True)
>>> hist
array([ 0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
>>> hist.sum()
2.4999999999999996
>>> np.sum(hist*np.diff(bin_edges))
1.0
histogram
1D histogram
histogramdd
Multidimensional histogram
Notes
When normed is True, then the returned histogram is the sample density, defined such that:
X ny1
nx1 X
Hi,j xi yj = 1
i=0 j=0
Examples
2
2 1 0 1 2
If False, returns the number of samples in each bin. If True, returns the bin density, ie,
the bin count divided by the bin hypervolume.
weights : array_like (N,), optional
An array of values w_i weighing each sample (x_i, y_i, z_i, ...). Weights are normalized
to 1 if normed is True. If normed is False, the values of the returned histogram are equal
to the sum of the weights belonging to the samples falling into each bin.
Returns
H : ndarray
The multidimensional histogram of sample x. See normed and weights for the different
possible semantics.
edges : list
A list of D arrays describing the bin edges for each dimension.
See Also:
histogram
1D histogram
histogram2d
2D histogram
Examples
>>> r = np.random.randn(100,3)
>>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
>>> H.shape, edges[0].size, edges[1].size, edges[2].size
((5, 8, 4), 6, 9, 5)
bincount(x, weights=None)
Count number of occurrences of each value in array of non-negative ints.
The number of bins (of size 1) is one larger than the largest value in x. Each bin gives the number of occurrences
of its index value in x. If weights is specified the input array is weighted by it, i.e. if a value n is found at position
i, out[n] += weight[i] instead of out[n] += 1.
Parameters
x : array_like, 1 dimension, nonnegative ints
Input array.
weights : array_like, optional
Weights, array of the same shape as x.
Returns
out : ndarray of ints
The result of binning the input array. The length of out is equal to np.amax(x)+1.
Raises
ValueError :
If the input is not 1-dimensional, or contains elements with negative values.
TypeError :
If the type of the input is float or complex.
See Also:
histogram, digitize, unique
Examples
>>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])
A possible use of bincount is to perform sums over variable-size chunks of an array, using the weights
keyword.
digitize(x, bins)
Return the indices of the bins to which each value in input array belongs.
Each index i returned is such that bins[i-1] <= x < bins[i] if bins is monotonically increasing, or
bins[i-1] > x >= bins[i] if bins is monotonically decreasing. If values in x are beyond the bounds of
bins, 0 or len(bins) is returned as appropriate.
Parameters
x : array_like
Input array to be binned. It has to be 1-dimensional.
bins : array_like
Array of bins. It has to be 1-dimensional and monotonic.
Returns
out : ndarray of ints
Output array of indices, of same shape as x.
Raises
ValueError :
If the input is not 1-dimensional, or if bins is not monotonic.
TypeError :
If the type of the input is complex.
See Also:
bincount, histogram, unique
Notes
If values in x are such that they fall outside the bin range, attempting to index bins with the indices that digitize
returns will result in an IndexError.
Examples
Notes
The sine is one of the fundamental functions of trigonometry (the mathematical study of triangles). Consider
a circle of radius 1 centered on the origin. A ray comes in from the +x axis, makes an angle at the origin
(measured counter-clockwise from that axis), and departs from the origin. The y coordinate of the outgoing
rays intersection with the unit circle is the sine of that angle. It ranges from -1 for x = 3/2 to +1 for /2.
The function has zeroes where the angle is a multiple of . Sines of angles between and 2 are negative. The
numerous properties of the sine and related functions are included in any standard trigonometry text.
Examples
Print sine of one angle:
>>> np.sin(np.pi/2.)
1.0
1.0
0.5
sin(x)
0.0
0.5
1.0
3 2 1 0 1 2 3
Angle [rad]
cos
Cosine elementwise.
Parameters
x : array_like
Input array in radians.
Notes
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
References
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972.
Examples
tan
Compute tangent element-wise.
Equivalent to np.sin(x)/np.cos(x) element-wise.
Parameters
x : array_like
Input array.
out : ndarray, optional
Output array of same shape as x.
Returns
y : ndarray
The corresponding tangent values.
Raises
ValueError: invalid return array shape :
if out is provided and out.shape != x.shape (See Examples)
Notes
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
References
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972.
Examples
arcsin
Inverse sine elementwise.
Parameters
x : array_like
y-coordinate on the unit circle.
out : ndarray, optional
Array of the same shape as x, to store results in. See doc.ufuncs (Section Output
arguments) for more details.
Returns
angle : ndarray
The angle of the ray intersecting the unit circle at the given y-coordinate in radians
[-pi, pi]. If x is a scalar then a scalar is returned, otherwise an array is returned.
See Also:
sin, cos, arccos, tan, arctan, arctan2, emath.arcsin
Notes
arcsin is a multivalued function: for each x there are infinitely many numbers z such that sin(z) = x. The
convention is to return the angle z whose real part lies in [-pi/2, pi/2].
For real-valued input data types, arcsin always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, arcsin is a complex analytical function that has branch cuts [-inf, -1] and [1, inf] and
is continuous from above on the former and from below on the latter.
The inverse sine is also known as asin or sin^-1.
References
[R6], [R7]
Examples
arccos
Trigonometric inverse cosine, element-wise.
The inverse of cos so that, if y = cos(x), then x = arccos(y).
Parameters
x : array_like
x-coordinate on the unit circle. For real arguments, the domain is [-1, 1].
out : ndarray, optional
Array of the same shape as a, to store results in. See doc.ufuncs (Section Output
arguments) for more details.
Returns
angle : ndarray
The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0,
pi]. If x is a scalar then a scalar is returned, otherwise an array of the same shape as x is
returned.
See Also:
cos, arctan, arcsin, emath.arccos
Notes
arccos is a multivalued function: for each x there are infinitely many numbers z such that cos(z) = x. The
convention is to return the angle z whose real part lies in [0, pi].
For real-valued input data types, arccos always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, arccos is a complex analytical function that has branch cuts [-inf, -1] and [1, inf] and
is continuous from above on the former and from below on the latter.
The inverse cos is also known as acos or cos^-1.
References
[R2], [R3]
Examples
We expect the arccos of 1 to be 0, and of -1 to be pi:
Plot arccos:
3.0
2.5
2.0
1.5
1.0
0.5
0.0
1.0 0.5 0.0 0.5 1.0
arctan
Trigonometric inverse tangent, element-wise.
The inverse of tan, so that if y = tan(x) then x = arctan(y).
Parameters
x : array_like
Input values. arctan is applied to each element of x.
Returns
out : ndarray
Out has the same shape as x. Its real part is in [-pi/2, pi/2]. It is a scalar if x is a
scalar.
See Also:
arctan2
Calculate the arctan of y/x.
Notes
arctan is a multivalued function: for each x there are infinitely many numbers z such that tan(z) = x. The
convention is to return the angle z whose real part lies in [-pi/2, pi/2].
For real-valued input data types, arctan always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, arctan is a complex analytical function that has branch cuts [1j, infj] and [-1j, -infj]
and is continuous from the left on the former and from the right on the latter.
The inverse tangent is also known as atan or tan^-1.
References
[R10], [R11]
Examples
We expect the arctan of 0 to be 0, and of 1 to be /4:
>>> np.pi/4
0.78539816339744828
Plot arctan:
1.0
0.5
0.0
0.5
1.0
10 5 0 5 10
hypot
Given the legs of a right triangle, return its hypotenuse.
Equivalent to sqrt(x1**2 + x2**2), element-wise. If x1 or x2 is scalar_like (i.e., unambiguously cast-
able to a scalar type), it is broadcast for use with each element of the other argument. (See Examples)
Parameters
x1, x2 : array_like
Leg of the triangle(s).
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
z : ndarray
Examples
arctan2
Elementwise arc tangent of x1/x2 choosing the quadrant correctly.
The quadrant (ie. branch) is chosen so that arctan2(x1, x2) is the signed angle in radians between the line
segments (0,0) - (1,0) and (0,0) - (x2,x1). This function is defined also for x2 = 0.
arctan2 is not defined for complex-valued arguments.
Parameters
x1 : array_like, real-valued
y-coordinates.
x2 : array_like, real-valued
x-coordinates. x2 must be broadcastable to match the shape of x1, or vice versa.
Returns
angle : ndarray
Array of angles in radians, in the range [-pi, pi].
See Also:
arctan, tan
Notes
arctan2 is identical to the atan2 function of the underlying C library. The following special values are defined
in the C standard [2]:
x1 x2 arctan2(x1,x2)
+/- 0 +0 +/- 0
+/- 0 -0 +/- pi
>0 +/-inf +0 / +pi
<0 +/-inf -0 / -pi
+/-inf +inf +/- (pi/4)
+/-inf -inf +/- (3*pi/4)
Note that +0 and -0 are distinct floating point numbers.
References
[R12], [R13]
Examples
Consider four points in different quadrants:
Note the order of the parameters. arctan2 is defined also when x2 = 0 and at several other special points,
obtaining values in the range [-pi, pi]:
degrees
Convert angles from radians to degrees.
Parameters
x : array_like
Input array in radians.
out : ndarray, optional
Output array of same shape as x.
Returns
y : ndarray of floats
The corresponding degree values.
See Also:
rad2deg
equivalent function
Examples
Convert a radian array to degrees
radians
Convert angles from degrees to radians.
Parameters
x : array_like
Input array in degrees.
deg2rad
equivalent function
Examples
Convert a degree array to radians
Notes
If the discontinuity in p is smaller than pi, but larger than discont, no unwrapping is done because taking the
2*pi complement would only make the discontinuity larger.
Examples
deg2rad
Convert angles from degrees to radians.
Parameters
x : array_like
Angles in degrees.
Returns
y : ndarray
The corresponding angle in radians.
See Also:
rad2deg
Convert angles from radians to degrees.
unwrap
Remove large jumps in angle by wrapping.
Notes
New in version 1.3.0. deg2rad(x) is x * pi / 180.
Examples
>>> np.deg2rad(180)
3.1415926535897931
rad2deg
Convert angles from radians to degrees.
Parameters
x : array_like
Angle in radians.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
y : ndarray
The corresponding angle in degrees.
See Also:
deg2rad
Convert angles from degrees to radians.
unwrap
Remove large jumps in angle by wrapping.
Notes
New in version 1.3.0. rad2deg(x) is 180 * x / pi.
Examples
>>> np.rad2deg(np.pi/2)
90.0
Notes
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
References
M. Abramowitz and I. A. Stegun, Handbook of Mathematical Functions. New York, NY: Dover, 1972, pg. 83.
Examples
>>> np.sinh(0)
0.0
>>> np.sinh(np.pi*1j/2)
1j
>>> np.sinh(np.pi*1j) # (exact value is 0)
1.2246063538223773e-016j
>>> # Discrepancy due to vagaries of floating point arithmetic.
cosh
Hyperbolic cosine, element-wise.
Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j*x).
Parameters
x : array_like
Input array.
Returns
out : ndarray
Output array of same shape as x.
Examples
>>> np.cosh(0)
1.0
30
25
20
15
10
5
0
4 3 2 1 0 1 2 3 4
tanh
Compute hyperbolic tangent element-wise.
Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).
Parameters
x : array_like
Input array.
out : ndarray, optional
Output array of same shape as x.
Returns
y : ndarray
The corresponding hyperbolic tangent values.
Raises
ValueError: invalid return array shape :
if out is provided and out.shape != x.shape (See Examples)
Notes
If out is provided, the function writes the result into it, and returns a reference to out. (See Examples)
References
[R272], [R273]
Examples
arcsinh
Inverse hyperbolic sine elementwise.
Parameters
x : array_like
Input array.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
out : ndarray
Array of of the same shape as x.
Notes
arcsinh is a multivalued function: for each x there are infinitely many numbers z such that sinh(z) = x. The
convention is to return the z whose imaginary part lies in [-pi/2, pi/2].
For real-valued input data types, arcsinh always returns real output. For each value that cannot be expressed as
a real number or infinity, it returns nan and sets the invalid floating point error flag.
For complex-valued input, arccos is a complex analytical function that has branch cuts [1j, infj] and [-1j, -infj]
and is continuous from the right on the former and from the left on the latter.
The inverse hyperbolic sine is also known as asinh or sinh^-1.
References
[R8], [R9]
Examples
arccosh
Inverse hyperbolic cosine, elementwise.
Parameters
x : array_like
Input array.
out : ndarray, optional
Array of the same shape as x, to store results in. See doc.ufuncs (Section Output
arguments) for details.
Returns
y : ndarray
Array of the same shape as x.
See Also:
cosh, arcsinh, sinh, arctanh, tanh
Notes
arccosh is a multivalued function: for each x there are infinitely many numbers z such that cosh(z) = x. The
convention is to return the z whose imaginary part lies in [-pi, pi] and the real part in [0, inf].
For real-valued input data types, arccosh always returns real output. For each value that cannot be expressed as
a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, arccosh is a complex analytical function that has a branch cut [-inf, 1] and is contin-
uous from above on it.
References
[R4], [R5]
Examples
arctanh
Inverse hyperbolic tangent elementwise.
Parameters
x : array_like
Input array.
Returns
out : ndarray
Array of the same shape as x.
See Also:
emath.arctanh
Notes
arctanh is a multivalued function: for each x there are infinitely many numbers z such that tanh(z) = x. The
convention is to return the z whose imaginary part lies in [-pi/2, pi/2].
For real-valued input data types, arctanh always returns real output. For each value that cannot be expressed as
a real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, arctanh is a complex analytical function that has branch cuts [-1, -inf] and [1, inf]
and is continuous from above on the former and from below on the latter.
The inverse hyperbolic tangent is also known as atanh or tanh^-1.
References
[R14], [R15]
Examples
3.13.3 Rounding
ndarray.round
equivalent method
Notes
For values exactly halfway between rounded decimal values, Numpy rounds to the nearest even value. Thus
1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact
representation of decimal fractions in the IEEE floating point standard [R16] and errors introduced when scaling
by powers of ten.
References
[R16], [R17]
Examples
around
equivalent function
rint
Round elements of the array to the nearest integer.
Parameters
x : array_like
Input array.
Returns
out : {ndarray, scalar}
Output array is same shape and type as x.
See Also:
ceil, floor, trunc
Examples
fix(x, y=None)
Round to nearest integer towards zero.
Round an array of floats element-wise to nearest integer towards zero. The rounded values are returned as floats.
Parameters
x : array_like
An array of floats to be rounded
y : ndarray, optional
Output array
Returns
out : ndarray of floats
The array of rounded numbers
See Also:
trunc, floor, ceil
around
Round to given number of decimals
Examples
>>> np.fix(3.14)
3.0
>>> np.fix(3)
3.0
>>> np.fix([2.1, 2.9, -2.1, -2.9])
array([ 2., 2., -2., -2.])
floor
Return the floor of the input, element-wise.
The floor of the scalar x is the largest integer i, such that i . It is often denoted as bxc.
Parameters
x : array_like
Input data.
Returns
y : {ndarray, scalar}
The floor of each element in x.
See Also:
ceil, trunc, rint
Notes
Some spreadsheet programs calculate the floor-towards-zero, in other words floor(-2.5) == -2.
NumPy, however, uses the a definition of floor such that floor(-2.5) == -3.
Examples
ceil
Return the ceiling of the input, element-wise.
The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as dxe.
Parameters
x : array_like
Input data.
Returns
y : {ndarray, scalar}
The ceiling of each element in x, with float dtype.
See Also:
floor, trunc, rint
Examples
trunc
Return the truncated value of the input, element-wise.
The truncated value of the scalar x is the nearest integer i which is closer to zero than x is. In short, the fractional
part of the signed number x is discarded.
Parameters
x : array_like
Input data.
Returns
y : {ndarray, scalar}
The truncated value of each element in x.
See Also:
ceil, floor, rint
Notes
New in version 1.3.0.
Examples
prod(a[, axis, dtype, out]) Return the product of array elements over a given axis.
sum(a[, axis, dtype, out]) Sum of array elements over a given axis.
nansum(a[, axis]) Return the sum of array elements over a given axis treating
cumprod(a[, axis, dtype, out]) Return the cumulative product of elements along a given axis.
cumsum(a[, axis, dtype, out]) Return the cumulative sum of the elements along a given axis.
diff(a[, n, axis]) Calculate the n-th order discrete difference along given axis.
ediff1d(ary[, to_end, to_begin]) The differences between consecutive elements of an array.
gradient(f, *varargs) Return the gradient of an N-dimensional array.
cross(a, b[, axisa, axisb, axisc, axis]) Return the cross product of two (arrays of) vectors.
trapz(y[, x, dx, axis]) Integrate along the given axis using the composite trapezoidal rule.
ndarray.prod
equivalent method
numpy.doc.ufuncs
Section Output arguments
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow. That means that, on a 32-bit
platform:
Examples
By default, calculate the product of all elements:
>>> np.prod([1.,2.])
2.0
>>> np.prod([[1.,2.],[3.,4.]])
24.0
If the type of x is unsigned, then the output type is the unsigned platform integer:
If x is of a signed integer type, then the output type is the default platform integer:
ndarray.sum
Equivalent method.
cumsum
Cumulative sum of array elements.
trapz
Integration of array values using the composite trapezoidal rule.
mean, average
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
nansum(a, axis=None)
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
Parameters
a : array_like
Array containing numbers whose sum is desired. If a is not an array, a conversion is
attempted.
axis : int, optional
Axis along which the sum is computed. The default is to compute the sum of the
flattened array.
Returns
y : ndarray
An array with the same shape as a, with the specified axis removed. If a is a 0-d array,
or if axis is None, a scalar is returned with the same dtype as a.
See Also:
numpy.sum
Sum across array including Not a Numbers.
isnan
Shows which elements are Not a Number (NaN).
isfinite
Shows which elements are not: Not a Number, positive and negative infinity
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a
Number is not equivalent to infinity. If positive or negative infinity are present the result is positive or negative
infinity. But if both positive and negative infinity are present, the result is Not A Number (NaN).
Arithmetic is modular when using integer types (all elements of a must be finite i.e. no elements that are NaNs,
positive infinity and negative infinity because NaNs are floating point types), and no error is raised on overflow.
Examples
>>> np.nansum(1)
1
>>> np.nansum([1])
1
>>> np.nansum([1, np.nan])
1.0
>>> a = np.array([[1, 1], [1, np.nan]])
>>> np.nansum(a)
3.0
>>> np.nansum(a, axis=0)
array([ 2., 1.])
numpy.doc.ufuncs
Section Output arguments
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> a = np.array([1,2,3])
>>> np.cumprod(a) # intermediate results 1, 1*2
... # total product 1*2*3 = 6
array([1, 2, 6])
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> np.cumprod(a, dtype=float) # specify type of output
array([ 1., 2., 6., 24., 120., 720.])
The cumulative product for each column (i.e., over the rows of) a:
The cumulative product for each row (i.e. over the columns of) a:
>>> np.cumprod(a,axis=1)
array([[ 1, 2, 6],
[ 4, 20, 120]])
sum
Sum array elements.
trapz
Integration of array values using the composite trapezoidal rule.
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
Examples
array([ 1, 2, 3, -7])
>>> np.diff(x, n=2)
array([ 1, 1, -10])
Notes
When applied to masked arrays, this function drops the mask information if the to_begin and/or to_end param-
eters are used.
Examples
gradient(f, *varargs)
Return the gradient of an N-dimensional array.
The gradient is computed using central differences in the interior and first differences at the boundaries. The
returned gradient hence has the same shape as the input array.
Parameters
f : array_like
An N-dimensional array containing samples of a scalar function.
*varargs : scalars
0, 1, or N scalars specifying the sample distances in each direction, that is: dx, dy, dz,
... The default distance is 1.
Returns
g : ndarray
N arrays of the same shape as f giving the derivative of f with respect to each dimension.
Examples
If defined, the axis of a, b and c that defines the vector(s) and cross product(s). Overrides
axisa, axisb and axisc.
Returns
c : ndarray
Vector cross product(s).
Raises
ValueError :
When the dimension of the vector(s) in a and/or b does not equal 2 or 3.
See Also:
inner
Inner product
outer
Outer product.
ix_
Construct index arrays.
Examples
Vector cross-product.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([-3, 6, -3])
>>> x = [1, 2]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
Equivalently:
>>> x = [1, 2, 0]
>>> y = [4, 5, 6]
>>> np.cross(x, y)
array([12, -6, -3])
>>> x = [1,2]
>>> y = [4,5]
>>> np.cross(x, y)
-3
Multiple vector cross-products. Note that the direction of the cross product vector is defined by the right-hand
rule.
Notes
Image [R275] illustrates trapezoidal rule y-axis locations of points will be taken from y array, by default x-axis
distances between points will be 1.0, alternatively they can be provided with x array or with dx scalar. Return
value will be equal to combined area under the red lines.
References
[R274], [R275]
Examples
>>> np.trapz([1,2,3])
4.0
>>> np.trapz([1,2,3], x=[4,6,8])
8.0
>>> np.trapz([1,2,3], dx=2)
8.0
>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.trapz(a, axis=0)
array([ 1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([ 2., 8.])
expm1
Calculate exp(x) - 1 for all elements in the array.
exp2
Calculate 2**x for all elements in the array.
Notes
The irrational number e is also known as Eulers number. It is approximately 2.718281, and is the base of the
natural logarithm, ln (this means that, if x = ln y = loge y, then ex = y. For real input, exp(x) is always
positive.
For complex arguments, x = a + ib, we can write ex = ea eib . The first term, ea , is already known (it is
the real argument, described above). The second term, eib , is cos b + i sin b, a function with magnitude 1 and a
periodic phase.
References
[R28], [R29]
Examples
Plot the magnitude and phase of exp(x) in the complex plane:
>>> plt.subplot(121)
>>> plt.imshow(np.abs(out),
... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi])
>>> plt.title(Magnitude of exp(x))
>>> plt.subplot(122)
>>> plt.imshow(np.angle(out),
... extent=[-2*np.pi, 2*np.pi, -2*np.pi, 2*np.pi])
>>> plt.title(Phase (angle) of exp(x))
>>> plt.show()
expm1
Calculate exp(x) - 1 for all elements in the array.
Parameters
x : array_like
Input values.
Returns
out : ndarray
Element-wise exponential minus one: out = exp(x) - 1.
See Also:
log1p
log(1 + x), the inverse of expm1.
Notes
This function provides greater precision than the formula exp(x) - 1 for small values of x.
Examples
The true value of exp(1e-10) - 1 is 1.00000000005e-10 to about 32 significant digits. This example
shows the superiority of expm1 in this case.
>>> np.expm1(1e-10)
1.00000000005e-10
>>> np.exp(1e-10) - 1
1.000000082740371e-10
exp2
Calculate 2**p for all p in the input array.
Parameters
x : array_like
Input values.
out : ndarray, optional
Array to insert results into.
Returns
out : ndarray
Element-wise 2 to the power x.
See Also:
exp
calculate x**p.
Notes
New in version 1.3.0.
Examples
log
Natural logarithm, element-wise.
The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm
is logarithm in base e.
Parameters
x : array_like
Input value.
Returns
y : ndarray
The natural logarithm of x, element-wise.
See Also:
log10, log2, log1p, emath.log
Notes
Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = x. The
convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log is a complex analytical function that has a branch cut [-inf, 0] and is continuous
from above on it. log handles the floating-point negative zero as an infinitesimal negative number, conforming
to the C99 standard.
References
[R51], [R52]
Examples
log10
Return the base 10 logarithm of the input array, element-wise.
Parameters
x : array_like
Input values.
Returns
y : ndarray
The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative.
See Also:
emath.log10
Notes
Logarithm is a multivalued function: for each x there is an infinite number of z such that 10**z = x. The
convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log10 always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log10 is a complex analytical function that has a branch cut [-inf, 0] and is continuous
from above on it. log10 handles the floating-point negative zero as an infinitesimal negative number, conforming
to the C99 standard.
References
[R53], [R54]
Examples
log2
Base-2 logarithm of x.
Parameters
x : array_like
Input values.
Returns
y : ndarray
Base-2 logarithm of x.
See Also:
log, log10, log1p, emath.log2
Notes
New in version 1.3.0. Logarithm is a multivalued function: for each x there is an infinite number of z such that
2**z = x. The convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log2 always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log2 is a complex analytical function that has a branch cut [-inf, 0] and is continuous
from above on it. log2 handles the floating-point negative zero as an infinitesimal negative number, conforming
to the C99 standard.
Examples
log1p
Return the natural logarithm of one plus the input array, element-wise.
Calculates log(1 + x).
Parameters
x : array_like
Input values.
Returns
y : ndarray
Natural logarithm of 1 + x, element-wise.
See Also:
expm1
exp(x) - 1, the inverse of log1p.
Notes
For real-valued input, log1p is accurate also for x so small that 1 + x == 1 in floating-point accuracy.
Logarithm is a multivalued function: for each x there is an infinite number of z such that exp(z) = 1 + x. The
convention is to return the z whose imaginary part lies in [-pi, pi].
For real-valued input data types, log1p always returns real output. For each value that cannot be expressed as a
real number or infinity, it yields nan and sets the invalid floating point error flag.
For complex-valued input, log1p is a complex analytical function that has a branch cut [-inf, -1] and is con-
tinuous from above on it. log1p handles the floating-point negative zero as an infinitesimal negative number,
conforming to the C99 standard.
References
[R55], [R56]
Examples
>>> np.log1p(1e-99)
1e-99
>>> np.log(1 + 1e-99)
0.0
logaddexp
Logarithm of the sum of exponentiations of the inputs.
Calculates log(exp(x1) + exp(x2)). This function is useful in statistics where the calculated proba-
bilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the
logarithm of the calculated probability is stored. This function allows adding probabilities stored in such a
fashion.
Parameters
x1, x2 : array_like
Input values.
Returns
result : ndarray
Logarithm of exp(x1) + exp(x2).
See Also:
logaddexp2
Logarithm of the sum of exponentiations of inputs in base-2.
Notes
New in version 1.3.0.
Examples
logaddexp2
Logarithm of the sum of exponentiations of the inputs in base-2.
Calculates log2(2**x1 + 2**x2). This function is useful in machine learning when the calculated prob-
abilities of events may be so small as to exceed the range of normal floating point numbers. In such cases the
base-2 logarithm of the calculated probability can be used instead. This function allows adding probabilities
stored in such a fashion.
Parameters
x1, x2 : array_like
Input values.
out : ndarray, optional
Array to store results in.
Returns
result : ndarray
Base-2 logarithm of 2**x1 + 2**x2.
See Also:
logaddexp
Logarithm of the sum of exponentiations of the inputs.
Notes
New in version 1.3.0.
Examples
Parameters
x : array_like, dtype float or complex
Argument of the Bessel function.
Returns
out : ndarray, shape = x.shape, dtype = x.dtype
The modified Bessel function evaluated at each of the elements of x.
Raises
TypeError: array cannot be safely cast to required type :
If argument consists exclusively of int dtypes.
See Also:
scipy.special.iv, scipy.special.ive
Notes
We use the algorithm published by Clenshaw [R38] and referenced by Abramowitz and Stegun [R39], for which
the function domain is partitioned into the two intervals [0,8] and (8,inf), and Chebyshev polynomial expansions
are employed in each interval. Relative error on the domain [0,30] using IEEE arithmetic is documented [R40]
as having a peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).
References
[R38], [R39], [R40]
Examples
>>> np.i0([0.])
array(1.0)
>>> np.i0([0., 1. + 2j])
array([ 1.00000000+0.j , 0.18785373+0.64616944j])
sinc(x)
Return the sinc function.
The sinc function is sin(x)/(x).
Parameters
x : ndarray
Array (possibly multi-dimensional) of values for which to to calculate sinc(x).
Returns
out : ndarray
sinc(x), which has the same shape as the input.
Notes
sinc(0) is the limit value 1.
The name sinc is short for sine cardinal or sinus cardinalis.
The sinc function is used in various signal processing applications, including in anti-aliasing, in the construction
of a Lanczos resampling filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal interpolation kernel is proportional to the sinc
function.
References
[R270], [R271]
Examples
Sinc Function
0
100
Amplitude
200
300
400
0 100 200 300 400
X
signbit() Returns element-wise True where signbit is set (less than zero).
copysign(x1) Change the sign of x1 to that of x2, element-wise.
frexp(out1) Split the number, x, into a normalized fraction (y1) and exponent (y2)
ldexp(x1) Compute y = x1 * 2**x2.
signbit
Returns element-wise True where signbit is set (less than zero).
Parameters
x: array_like :
The input value(s).
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
out : array_like, bool
Output array.
Examples
>>> np.signbit(-1.2)
True
>>> np.signbit(np.array([1, -2.3, 2.1]))
array([False, True, False], dtype=bool)
copysign
Change the sign of x1 to that of x2, element-wise.
If both arguments are arrays or sequences, they have to be of the same length. If x2 is a scalar, its sign will be
copied to all elements of x1.
Parameters
x1: array_like :
Values to change the sign of.
x2: array_like :
The sign of x2 is copied to x1.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
out : array_like
The values of x1 with the sign of x2.
Examples
frexp
Split the number, x, into a normalized fraction (y1) and exponent (y2)
ldexp
Compute y = x1 * 2**x2.
Parameters
x1, x2 : array_like
The arrays to be added.
Returns
y : {ndarray, scalar}
The sum of x1 and x2, element-wise. Returns scalar if both x1 and x2 are scalars.
Notes
Equivalent to x1 + x2 in terms of array broadcasting.
Examples
reciprocal
Return the reciprocal of the argument, element-wise.
Calculates 1/x.
Parameters
x : array_like
Input array.
Returns
y : ndarray
Return array.
Notes
Note: This function is not designed to work with integers.
For integer arguments with absolute value larger than 1 the result is always zero because of the way Python
handles integer division. For integer zero the result is an overflow.
Examples
>>> np.reciprocal(2.)
0.5
>>> np.reciprocal([1, 2., 3.33])
array([ 1. , 0.5 , 0.3003003])
negative
Returns an array with the negative of each element of the original array.
Parameters
x : {array_like, scalar}
Input array.
Returns
y : {ndarray, scalar}
Returned array or scalar y=-x.
Examples
>>> np.negative([1.,-1.])
array([-1., 1.])
multiply
Multiply arguments element-wise.
Parameters
x1, x2 : array_like
Input arrays to be multiplied.
Returns
y : ndarray
The product of x1 and x2, element-wise. Returns a scalar if both x1 and x2 are scalars.
Notes
Equivalent to x1 * x2 in terms of array broadcasting.
Examples
divide
Divide arguments element-wise.
Parameters
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
y : {ndarray, scalar}
The quotient x1/x2, element-wise. Returns a scalar if both x1 and x2 are scalars.
See Also:
seterr
Set whether to raise or warn on overflow, underflow and division by zero.
Notes
Equivalent to x1 / x2 in terms of array-broadcasting.
Behavior on division by zero can be changed using seterr.
When both x1 and x2 are of an integer type, divide will return integers and throw away the fractional part.
Moreover, division by zero always yields zero in integer arithmetic.
Examples
>>> np.divide(2, 4)
0
>>> np.divide(2, 4.)
0.5
Division by zero always yields zero in integer arithmetic, and does not raise an exception or a warning:
power
Returns element-wise base array raised to power from second array.
Raise each base in x1 to the power of the exponents in x2. This requires that x1 and x2 must be broadcastable to
the same shape.
Parameters
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
y : ndarray
The bases in x1 raised to the exponents in x2.
Examples
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
subtract
Subtract arguments, element-wise.
Parameters
x1, x2 : array_like
The arrays to be subtracted from each other.
Returns
y : ndarray
The difference of x1 and x2, element-wise. Returns a scalar if both x1 and x2 are scalars.
Notes
Equivalent to x1 - x2 in terms of array broadcasting.
Examples
true_divide
Returns a true division of the inputs, element-wise.
Instead of the Python traditional floor division, this returns a true division. True division adjusts the output
type to present the best answer, regardless of input types.
Parameters
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
Returns
out : ndarray
Result is scalar if both inputs are scalar, ndarray otherwise.
Notes
The floor division operator // was added in Python 2.2 making // and / equivalent operators. The default floor
division operation of / can be replaced by true division with from __future__ import division.
In Python 3.0, // is the floor division operator and / the true division operator. The true_divide(x1,
x2) function is equivalent to true division in Python.
Examples
>>> x = np.arange(5)
>>> np.true_divide(x, 4)
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
>>> x/4
array([0, 0, 0, 0, 1])
>>> x//4
array([0, 0, 0, 0, 1])
floor_divide
Return the largest integer smaller or equal to the division of the inputs.
Parameters
x1 : array_like
Numerator.
x2 : array_like
Denominator.
Returns
y : ndarray
y = floor(x1/x2)
See Also:
divide
Standard division.
floor
Round a number to the nearest integer toward minus infinity.
ceil
Round a number to the nearest integer toward infinity.
Examples
>>> np.floor_divide(7,3)
2
>>> np.floor_divide([1., 2., 3., 4.], 2.5)
array([ 0., 0., 1., 1.])
fmod
Return the element-wise remainder of division.
This is the NumPy implementation of the Python modulo operator %.
Parameters
x1 : array_like
Dividend.
x2 : array_like
Divisor.
Returns
y : array_like
The remainder of the division of x1 by x2.
See Also:
remainder
Modulo operation where the quotient is floor(x1/x2).
divide
Notes
The result of the modulo operation for negative dividend and divisors is bound by conventions. In fmod, the sign
of the remainder is the sign of the dividend. In remainder, the sign of the divisor does not affect the sign of the
result.
Examples
mod
Return element-wise remainder of division.
Computes x1 - floor(x1 / x2) * x2.
Parameters
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
y : ndarray
The remainder of the quotient x1/x2, element-wise. Returns a scalar if both x1 and x2
are scalars.
See Also:
divide, floor
Notes
Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers.
Examples
modf
Return the fractional and integral parts of an array, element-wise.
The fractional and integral parts are negative if the given number is negative.
Parameters
x : array_like
Input array.
Returns
y1 : ndarray
Fractional part of x.
y2 : ndarray
Integral part of x.
Notes
For integer input the return values are floats.
Examples
remainder
Return element-wise remainder of division.
Computes x1 - floor(x1 / x2) * x2.
Parameters
x1 : array_like
Dividend array.
x2 : array_like
Divisor array.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
y : ndarray
The remainder of the quotient x1/x2, element-wise. Returns a scalar if both x1 and x2
are scalars.
See Also:
divide, floor
Notes
Returns 0 when x2 is 0 and both x1 and x2 are (arrays of) integers.
Examples
Examples
real(val)
Return the real part of the elements of the array.
Parameters
val : array_like
Input array.
Returns
out : ndarray
Output array. If val is real, the type of val is used for the output. If val has complex
elements, the returned type is float.
See Also:
real_if_close, imag, angle
Examples
imag(val)
Return the imaginary part of the elements of the array.
Parameters
val : array_like
Input array.
Returns
out : ndarray
Output array. If val is real, the type of val is used for the output. If val has complex
elements, the returned type is float.
See Also:
real, angle, real_if_close
Examples
conj
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.
Parameters
x : array_like
Input value.
Returns
y : ndarray
The complex conjugate of x, with same dtype as y.
Examples
>>> np.conjugate(1+2j)
(1-2j)
3.13.10 Miscellaneous
convolve(a, v[, mode]) Returns the discrete, linear convolution of two one-dimensional sequences.
clip(a, a_min, a_max[, out]) Clip (limit) the values in an array.
sqrt() Return the positive square-root of an array, element-wise.
square() Return the element-wise square of the input.
absolute() Calculate the absolute value element-wise.
fabs() Compute the absolute values elementwise.
sign() Returns an element-wise indication of the sign of a number.
maximum(x1) Element-wise maximum of array elements.
minimum(x1) Element-wise minimum of array elements.
nan_to_num(x) Replace nan with zero and inf with finite numbers.
real_if_close(a[, tol]) If complex input returns a real array if complex parts are close to zero.
interp(x, xp, fp[, left, right]) One-dimensional linear interpolation.
convolve(a, v, mode=full)
Returns the discrete, linear convolution of two one-dimensional sequences.
The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant
system on a signal [R27]. In probability theory, the sum of two independent random variables is distributed
according to the convolution of their individual distributions.
Parameters
a : (N,) array_like
First one-dimensional input array.
v : (M,) array_like
Second one-dimensional input array.
mode : {full, valid, same}, optional
full:
By default, mode is full. This returns the convolution at each point of overlap, with
an output shape of (N+M-1,). At the end-points of the convolution, the signals do not
overlap completely, and boundary effects may be seen.
same:
Mode same returns output of length max(M, N). Boundary effects are still visible.
valid:
Mode valid returns output of length max(M, N) - min(M, N) + 1. The con-
volution product is only given for points where the signals overlap completely. Values
outside the signal boundary have no effect.
Returns
out : ndarray
Discrete, linear convolution of a and v.
See Also:
scipy.signal.fftconvolve
Convolve two arrays using the Fast Fourier Transform.
scipy.linalg.toeplitz
Used to construct the convolution operator.
Notes
The discrete convolution operation is defined as
X
(f g)[n] = f [m]g[n m]
m=
It can be shown that a convolution x(t) y(t) in time/space is equivalent to the multiplication X(f )Y (f ) in
the Fourier domain, after appropriate padding (padding is necessary to prevent circular convolution). Since
multiplication is more efficient (faster) than convolution, the function scipy.signal.fftconvolve exploits the FFT
to calculate the convolution of large data-sets.
References
[R27]
Examples
Note how the convolution operator flips the second array before sliding the two across one another:
Only return the middle values of the convolution. Contains boundary effects, where zeros are taken into account:
The two arrays are of the same length, so there is only one position where they completely overlap:
An array with the elements of a, but where values < a_min are replaced with a_min, and
those > a_max with a_max.
See Also:
numpy.doc.ufuncs
Section Output arguments
Examples
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
sqrt
Return the positive square-root of an array, element-wise.
Parameters
x : array_like
The square root of each element in this array is calculated.
Returns
y : ndarray
An array of the same shape as x, containing the square-root of each element in x. If any
element in x is complex, a complex array is returned. If all of the elements of x are real,
negative elements return numpy.nan elements.
See Also:
numpy.lib.scimath.sqrt
A version which returns complex numbers when given negative reals.
Notes
sqrt has a branch cut [-inf, 0) and is continuous from above on it.
Examples
>>> np.sqrt([1,4,9])
array([ 1., 2., 3.])
square
Return the element-wise square of the input.
Parameters
x : array_like
Input data.
Returns
out : ndarray
Element-wise x*x, of the same shape and dtype as x. Returns scalar if x is a scalar.
See Also:
numpy.linalg.matrix_power, sqrt, power
Examples
absolute
Calculate the absolute value element-wise.
Parameters
x : array_like
Input array.
Returns
res : ndarray
An ndarray containing theabsolute value of each element in x. For complex input, a +
ib, the absolute value is a2 + b2 .
Examples
10
10
10 5 0 5 10
fabs
Compute the absolute values elementwise.
This function returns the absolute values (positive magnitude) of the data in x. Complex values are not handled,
use absolute to find the absolute values of complex data.
Parameters
x : array_like
The array of numbers for which the absolute values are required. If x is a scalar, the
result y will also be a scalar.
out : ndarray, optional
Array into which the output is placed. Its type is preserved and it must be of the right
shape to hold the output. See doc.ufuncs.
Returns
y : {ndarray, scalar}
The absolute values of x, the returned values are always floats.
See Also:
absolute
Absolute values including complex types.
Examples
>>> np.fabs(-1)
1.0
>>> np.fabs([-1.2, 1.2])
array([ 1.2, 1.2])
sign
Returns an element-wise indication of the sign of a number.
The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0.
Parameters
x : array_like
Input values.
Returns
y : ndarray
The sign of x.
Examples
maximum
Element-wise maximum of array elements.
Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being
compared is a nan, then that element is returned. If both elements are nans then the first is returned. The latter
distinction is important for complex nans, which are defined as at least one of the real or imaginary parts being
a nan. The net effect is that nans are propagated.
Parameters
x1, x2 : array_like
The arrays holding the elements to be compared. They must have the same shape, or
shapes that can be broadcast to a single shape.
Returns
y : {ndarray, scalar}
The maximum of x1 and x2, element-wise. Returns scalar if both x1 and x2 are scalars.
See Also:
minimum
element-wise minimum
fmax
element-wise maximum that ignores nans unless both inputs are nans.
fmin
element-wise minimum that ignores nans unless both inputs are nans.
Notes
Equivalent to np.where(x1 > x2, x1, x2) but faster and does proper broadcasting.
Examples
minimum
Element-wise minimum of array elements.
Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being
compared is a nan, then that element is returned. If both elements are nans then the first is returned. The latter
distinction is important for complex nans, which are defined as at least one of the real or imaginary parts being
a nan. The net effect is that nans are propagated.
Parameters
x1, x2 : array_like
The arrays holding the elements to be compared. They must have the same shape, or
shapes that can be broadcast to a single shape.
Returns
y : {ndarray, scalar}
The minimum of x1 and x2, element-wise. Returns scalar if both x1 and x2 are scalars.
See Also:
maximum
element-wise minimum that propagates nans.
fmax
element-wise maximum that ignores nans unless both inputs are nans.
fmin
element-wise minimum that ignores nans unless both inputs are nans.
Notes
The minimum is equivalent to np.where(x1 <= x2, x1, x2) when neither x1 nor x2 are nans, but it is
faster and does proper broadcasting.
Examples
nan_to_num(x)
Replace nan with zero and inf with finite numbers.
Returns an array or scalar replacing Not a Number (NaN) with zero, (positive) infinity with a very large number
and negative infinity with a very small (or negative) number.
Parameters
x : array_like
Input data.
Returns
out : ndarray, float
Array with the same shape as x and dtype of the element in x with the greatest precision.
NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or
most negative) floating point value that fits in the output dtype. All finite numbers are
upcast to the output dtype (default float64).
See Also:
isinf
Shows which elements are negative or negative infinity.
isneginf
Shows which elements are negative infinity.
isposinf
Shows which elements are positive infinity.
isnan
Shows which elements are Not a Number (NaN).
isfinite
Shows which elements are finite (not NaN, not infinity)
Notes
Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic (IEEE 754). This means that Not a
Number is not equivalent to infinity.
Examples
>>> np.set_printoptions(precision=8)
>>> x = np.array([np.inf, -np.inf, np.nan, -128, 128])
>>> np.nan_to_num(x)
array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000,
-1.28000000e+002, 1.28000000e+002])
real_if_close(a, tol=100)
If complex input returns a real array if complex parts are close to zero.
Close to zero is defined as tol * (machine epsilon of the type for a).
Parameters
a : array_like
Input array.
tol : float
Tolerance in machine epsilons for the complex part of the elements in the array.
Returns
out : ndarray
If a is real, the type of a is used for the output. If a has complex elements, the returned
type is float.
See Also:
real, imag, angle
Notes
Machine epsilon varies from machine to machine and between data types but Python floats on most platforms
have a machine epsilon equal to 2.2204460492503131e-16. You can use np.finfo(np.float).eps to print out the
machine epsilon for floats.
Examples
>>> np.finfo(np.float).eps
2.2204460492503131e-16
Notes
Does not check that the x-coordinate sequence xp is increasing. If xp is not increasing, the results are nonsense.
A simple check for increasingness is:
np.all(np.diff(xp) > 0)
Examples
>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([ 3. , 3. , 2.5 , 0.56, 0. ])
>>> UNDEF = -99.0
>>> np.interp(3.14, xp, fp, right=UNDEF)
-99.0
1.0
0.5
0.0
0.5
1.0
0 1 2 3 4 5 6 7
apply_along_axis(func1d, axis, arr, *args) Apply a function to 1-D slices along the given axis.
apply_over_axes(func, a, axes) Apply a function repeatedly over multiple axes.
vectorize(pyfunc[, otypes, doc]) Generalized function class.
frompyfunc(func, nin, nout) Takes an arbitrary Python function and returns a Numpy ufunc.
piecewise(x, condlist, funclist, *args, **kw) Evaluate a piecewise-defined function.
apply_along_axis(func1d, axis, arr, *args)
Apply a function to 1-D slices along the given axis.
Execute func1d(a, *args) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.
Parameters
func1d : function
This function should accept 1-D arrays. It is applied to 1-D slices of arr along the
specified axis.
axis : integer
Axis along which arr is sliced.
arr : ndarray
Input array.
args : any
Additional arguments to func1d.
Returns
outarr : ndarray
The output array. The shape of outarr is identical to the shape of arr, except along the
axis dimension, where the length of outarr is equal to the size of the return value of
func1d. If func1d returns a scalar outarr will have one fewer dimensions than arr.
See Also:
apply_over_axes
Apply a function repeatedly over multiple axes.
Examples
For a function that doesnt return a scalar, the number of dimensions in outarr is the same as arr.
apply_over_axes(func, a, axes)
Apply a function repeatedly over multiple axes.
func is called as res = func(a, axis), where axis is the first element of axes. The result res of the function call must
have either the same dimensions as a or one less dimension. If res has one less dimension than a, a dimension
is inserted before axis. The call to func is then repeated for each axis in axes, with res as the first argument.
Parameters
func : function
This function must take two arguments, func(a, axis).
a : ndarray
Input array.
axes : array_like
Axes over which func is applied, the elements must be integers.
Returns
val : ndarray
The output array. The number of dimensions is the same as a, but the shape can be
different. This depends on whether func changes the shape of its output with respect to
its input.
See Also:
apply_along_axis
Apply a function to 1-D slices of an array along the given axis.
Examples
>>> a = np.arange(24).reshape(2,3,4)
>>> a
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
Sum over axes 0 and 2. The result has same number of dimensions as the original array:
Examples
The docstring is taken from the input function to vectorize unless it is specified
>>> vfunc.__doc__
Return a-b if a>b, otherwise return a+b
>>> vfunc = np.vectorize(myfunc, doc=Vectorized myfunc)
>>> vfunc.__doc__
Vectorized myfunc
The output type is determined by evaluating the first element of the input, unless it is specified
Notes
The returned ufunc always returns PyObject arrays.
Examples
Use frompyfunc to add broadcasting to the Python function oct:
Notes
This is similar to choose or select, except that functions are evaluated on elements of x that satisfy the corre-
sponding condition from condlist.
The result is:
|--
|funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
|...
|funclist[n2](x[condlist[n2]])
|--
Examples
Define the sigma function, which is -1 for x < 0 and +1 for x >= 0.
Define the absolute value, which is -x for x <0 and x for x >= 0.
3.15 Polynomials
3.15.1 Basics
Changes the variable used when printing p from x to variable (see Examples).
Examples
Construct the polynomial x2 + 2x + 3:
>>> p(0.5)
4.25
>>> p.r
array([-1.+1.41421356j, -1.-1.41421356j])
>>> p(p.r)
array([ -4.44089210e-16+0.j, -4.44089210e-16+0.j])
>>> p.c
array([1, 2, 3])
>>> p.order
2
Show the coefficient of the k-th power in the polynomial (which is equivalent to p.c[-(i+1)]):
>>> p[1]
2
Polynomials can be added, subtracted, multiplied, and divided (returns quotient and remainder):
>>> p * p
poly1d([ 1, 4, 10, 12, 9])
>>> (p**3 + 4) / p
(poly1d([ 1., 4., 10., 12., 9.]), poly1d([ 4.]))
asarray(p) gives the coefficient array, so polynomials can be used in all functions that accept arrays:
The variable used in the string representation of p can be modified, using the variable parameter:
Attributes
coeffs
order
variable
Methods
deriv([m]) Return a derivative of this polynomial.
integ([m, k]) Return an antiderivative (indefinite integral) of this polynomial.
deriv(m=1)
Return a derivative of this polynomial.
Refer to polyder for full documentation.
See Also:
polyder
equivalent function
integ(m=1, k=0)
Return an antiderivative (indefinite integral) of this polynomial.
Refer to polyint for full documentation.
See Also:
polyint
equivalent function
polyval(p, x)
Evaluate a polynomial at specific values.
If p is of length N, this function returns the value:
p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]
If x is a sequence, then p(x) is returned for each element of x. If x is another polynomial then the composite
polynomial p(x(t)) is returned.
Parameters
p : array_like or poly1d object
poly1d
A polynomial class.
Notes
Horners scheme [R68] is used to evaluate the polynomial. Even so, for polynomials of high degree the values
may be inaccurate due to rounding errors. Use carefully.
References
[R68]
Examples
poly(seq_of_zeros)
Find the coefficients of a polynomial with the given sequence of roots.
Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros
(multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square
matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the
characteristic polynomial of the matrix are returned.
Parameters
seq_of_zeros : array_like, shape (N,) or (N, N)
A sequence of polynomial roots, or a square array or matrix object.
Returns
c : ndarray
1D array of polynomial coefficients from highest to lowest degree:
c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]
where c[0] always equals 1.
Raises
ValueError :
If input is the wrong shape (the input must be a 1-D or square 2-D array).
See Also:
polyval
Evaluate a polynomial at a point.
roots
Return the roots of a polynomial.
polyfit
Least squares polynomial fit.
poly1d
A one-dimensional polynomial class.
Notes
Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined
leading coefficient. [R64] In the case of this function, that coefficient - the first one in the returned array - is
always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage
that information is to use polyfit.)
The characteristic polynomial, pa (t), of an n-by-n matrix A is given by
pa (t) = det(t I A),
where I is the n-by-n identity matrix. [R65]
References
[R64], [R65]
Examples
Given a sequence of a polynomials zeros:
>>> np.poly(np.matrix(P))
array([ 1. , 0. , 0.16666667])
poly
Find the coefficients of a polynomial with a given sequence of roots.
polyval
Evaluate a polynomial at a point.
polyfit
Least squares polynomial fit.
poly1d
A one-dimensional polynomial class.
Notes
The algorithm relies on computing the eigenvalues of the companion matrix [R267].
References
[R267]
Examples
3.15.2 Fitting
polyval
Computes polynomial values.
linalg.lstsq
Computes a least-squares fit.
scipy.interpolate.UnivariateSpline
Computes spline fits.
Notes
The solution minimizes the squared error
k
X
E= |p(xj ) yj |2
j=0
in the equations:
References
[R66], [R67]
Examples
>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179
>>> p(3.5)
-0.34732142857143039
>>> p(10)
22.579365079365115
Illustration:
>>> plt.ylim(-2,2)
(-2, 2)
>>> plt.show()
2.0
1.5
1.0
0.5
0.0
0.5
1.0
1.5
2.0
2 1 0 1 2 3 4 5 6
3.15.3 Calculus
polyint
Anti-derivative of a polynomial.
poly1d
Class for one-dimensional polynomials.
Examples
The derivative of the polynomial x3 + x2 + x1 + 1 is:
>>> p = np.poly1d([1,1,1,1])
>>> p2 = np.polyder(p)
>>> p2
poly1d([3, 2, 1])
>>> p2(2.)
17.0
>>> np.polyder(p, 2)
poly1d([6, 2])
>>> np.polyder(p, 3)
poly1d([6])
>>> np.polyder(p, 4)
poly1d([ 0.])
km1 0 k0
x + ... + xm1
0! (m 1)!
polyder
derivative of a polynomial
poly1d.integ
equivalent method
Examples
The defining property of the antiderivative:
>>> p = np.poly1d([1,1,1])
>>> P = np.polyint(p)
>>> P
poly1d([ 0.33333333, 0.5 , 1. , 0. ])
>>> np.polyder(P) == p
True
>>> P = np.polyint(p, 3)
>>> P(0)
0.0
>>> np.polyder(P)(0)
0.0
>>> np.polyder(P, 2)(0)
0.0
>>> P = np.polyint(p, 3, k=[6,5,3])
>>> P
poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ])
Note that 3 = 6 / 2!, and that the constants are given in the order of integrations. Constant of the highest-order
polynomial term comes first:
3.15.4 Arithmetic
The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d
object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest
degree.
See Also:
poly1d
A one-dimensional polynomial class.
Examples
polydiv(u, v)
Returns the quotient and remainder of polynomial division.
The input arrays are the coefficients (including any coefficients equal to zero) of the numerator (dividend) and
denominator (divisor) polynomials, respectively.
Parameters
u : array_like or poly1d
Dividend polynomials coefficients.
v : array_like or poly1d
Divisor polynomials coefficients.
Returns
q : ndarray
Coefficients, including those equal to zero, of the quotient.
r : ndarray
Coefficients, including those equal to zero, of the remainder.
See Also:
poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub, polyval
Notes
Both u and v must be 0-d or 1-d (ndim = 0 or 1), but u.ndim need not equal v.ndim. In other words, all four
possible combinations - u.ndim = v.ndim = 0, u.ndim = v.ndim = 1, u.ndim = 1, v.ndim
= 0, and u.ndim = 0, v.ndim = 1 - work.
Examples
3x2 + 5x + 2
= 1.5x + 1.75, remainder0.25
2x + 1
polymul(a1, a2)
Find the product of two polynomials.
Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either
a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree.
Parameters
a1, a2 : array_like or poly1d object
Input polynomials.
Returns
out : ndarray or poly1d object
The polynomial resulting from the multiplication of the inputs. If either inputs is a
poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of
polynomial coefficients from highest to lowest degree.
See Also:
poly1d
A one-dimensional polynomial class.
Examples
polysub(a1, a2)
Difference (subtraction) of two polynomials.
Given two polynomials a1 and a2, returns a1 - a2. a1 and a2 can be either array_like sequences of the
polynomials coefficients (including coefficients equal to zero), or poly1d objects.
Parameters
a1, a2 : array_like or poly1d
Minuend and subtrahend polynomials, respectively.
Returns
out : ndarray or poly1d
Array or poly1d object of the difference polynomials coefficients.
See Also:
polyval, polydiv, polymul, polyadd
Examples
3.15.5 Warnings
a present value, pv
an interest rate compounded once per period, of which there are
nper total
a (fixed) payment, pmt, paid either
at the beginning (when = {begin, 1}) or the end (when = {end, 0}) of each period
Return:
the value at the end of the nper periods
Parameters
rate : scalar or array_like of shape(M, )
Rate of interest as decimal (not per cent) per period
nper : scalar or array_like of shape(M, )
Number of compounding periods
pmt : scalar or array_like of shape(M, )
Payment
pv : scalar or array_like of shape(M, )
Present value
when : {{begin, 1}, {end, 0}}, {string, int}, optional
When payments are due (begin (1) or end (0)). Defaults to {end, 0}.
Returns
out : ndarray
Future values. If all input is scalar, returns a scalar float. If any input is array_like,
returns future values for each input element. If multiple inputs are array_like, they all
must have the same shape.
Notes
The future value is computed by solving the equation:
fv +
pv*(1+rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
fv + pv + pmt * nper == 0
References
[WRW]
Examples
What is the future value after 10 years of saving $100 now, with an additional monthly savings of $100. Assume
the interest rate is 5% (annually) compounded monthly?
By convention, the negative sign represents cash flow out (i.e. money not available today). Thus, saving $100 a
month at 5% annual interest leads to $15,692.93 available to spend in 10 years.
If any input is array_like, returns an array of equal shape. Lets compare different interest rates from the example
above.
a future value, fv
an interest rate compounded once per period, of which there are
nper total
a (fixed) payment, pmt, paid either
at the beginning (when = {begin, 1}) or the end (when = {end, 0}) of each period
Return:
the value now
Parameters
rate : array_like
Rate of interest (per period)
nper : array_like
Number of compounding periods
pmt : array_like
Payment
fv : array_like, optional
Future value
when : {{begin, 1}, {end, 0}}, {string, int}, optional
When payments are due (begin (1) or end (0))
Returns
out : ndarray, float
Present value of a series of payments or investments.
Notes
The present value is computed by solving the equation:
fv +
pv*(1 + rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0
fv + pv + pmt * nper = 0
References
[WRW]
Examples
What is the present value (e.g., the initial investment) of an investment that needs to total $15692.93 after 10
years of saving $100 every month? Assume the interest rate is 5% (annually) compounded monthly.
By convention, the negative sign represents cash flow out (i.e., money not available today). Thus, to end up with
$15,692.93 in 10 years saving $100 a month at 5% annual interest, ones initial deposit should also be $100.
If any input is array_like, pv returns an array of equal shape. Lets compare different interest rates in the
example above:
So, to end up with the same $15692.93 under the same $100 per month savings plan, for annual interest rates
of 4% and 3%, one would need initial investments of $649.27 and $1273.79, respectively.
npv(rate, values)
Returns the NPV (Net Present Value) of a cash flow series.
Parameters
rate : scalar
The discount rate.
values : array_like, shape(M, )
The values of the time series of cash flows. The (fixed) time interval between cash flow
events must be the same as that for which rate is given (i.e., if rate is per year, then
precisely a year is understood to elapse between each cash flow event). By convention,
investments or deposits are negative, income or withdrawals are positive; values
must begin with the initial investment, thus values[0] will typically be negative.
Returns
out : float
The NPV of the input cash flow series values at the discount rate.
Notes
Returns the result of: [G61]
M
X valuest
t=0
(1 + rate)t
References
[G61]
Examples
Parameters
rate : array_like
Rate of interest (per period)
nper : array_like
Number of compounding periods
pv : array_like
Present value
fv : array_like (optional)
Future value (default = 0)
when : {{begin, 1}, {end, 0}}, {string, int}
When payments are due (begin (1) or end (0))
Returns
out : ndarray
Payment against loan plus interest. If all input is scalar, returns a scalar float. If any
input is array_like, returns payment for each input element. If multiple inputs are ar-
ray_like, they all must have the same shape.
Notes
The payment is computed by solving the equation:
fv +
pv*(1 + rate)**nper +
pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
fv + pv + pmt * nper == 0
for pmt.
Note that computing a monthly mortgage payment is only one use for this function. For example, pmt returns the
periodic deposit one must make to achieve a specified future balance given an initial deposit, a fixed, periodically
compounded interest rate, and the total number of periods.
References
[WRW]
Examples
What is the monthly payment needed to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%?
In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained today, a monthly payment of $1,854.02
would be required. Note that this example illustrates usage of fv having a default value of 0.
ppmt(rate, per, nper, pv, fv=0.0, when=end)
Not implemented. Compute the payment against loan principal.
Parameters
rate : array_like
Rate of interest (per period)
per : array_like, int
Amount paid against the loan changes. The per is the period of interest.
nper : array_like
Number of compounding periods
pv : array_like
Present value
fv : array_like, optional
Future value
when : {{begin, 1}, {end, 0}}, {string, int}
When payments are due (begin (1) or end (0))
See Also:
pmt, pv, ipmt
ipmt(rate, per, nper, pv, fv=0.0, when=end)
Not implemented. Compute the payment portion for loan interest.
Parameters
rate : scalar or array_like of shape(M, )
Rate of interest as decimal (not per cent) per period
per : scalar or array_like of shape(M, )
Interest paid against the loan changes during the life or the loan. The per is the payment
period to calculate the interest amount.
nper : scalar or array_like of shape(M, )
Number of compounding periods
pv : scalar or array_like of shape(M, )
Present value
fv : scalar or array_like of shape(M, ), optional
Future value
when : {{begin, 1}, {end, 0}}, {string, int}, optional
When payments are due (begin (1) or end (0)). Defaults to {end, 0}.
Returns
out : ndarray
Interest portion of payment. If all input is scalar, returns a scalar float. If any input
is array_like, returns interest payment for each input element. If multiple inputs are
array_like, they all must have the same shape.
See Also:
ppmt, pmt, pv
Notes
The total payment is made up of payment against principal plus interest.
pmt = ppmt + ipmt
irr(values)
Return the Internal Rate of Return (IRR).
This is the average periodically compounded rate of return that gives a net present value of 0.0; for a more
complete explanation, see Notes below.
Parameters
values : array_like, shape(N,)
Input cash flows per time period. By convention, net deposits are negative and net
withdrawals are positive. Thus, for example, at least the first element of values, which
represents the initial investment, will typically be negative.
Returns
out : float
Internal Rate of Return for periodic input values.
Notes
The IRR is perhaps best understood through an example (illustrated using np.irr in the Examples section below).
Suppose one invests 100 units and then makes the following withdrawals at regular (fixed) intervals: 39, 59, 55,
20. Assuming the ending value is 0, ones 100 unit investment yields 173 units; however, due to the combi-
nation of compounding and the periodic withdrawals, the average rate of return is neither simply 0.73/4 nor
(1.73)^0.25-1. Rather, it is the solution (for r) of the equation:
39 59 55 20
100 + + 2
+ 3
+ =0
1 + r (1 + r) (1 + r) (1 + r)4
In general, for values = [v0 , v1 , ...vM ], irr is the solution of the equation: [G41]
M
X vt
=0
t=0
(1 + irr)t
References
[G41]
Examples
pv : array_like
Present value
fv : array_like, optional
Future value
when : {{begin, 1}, {end, 0}}, {string, int}, optional
When payments are due (begin (1) or end (0))
Notes
The number of periods nper is computed by solving the equation:
fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0
fv + pv + pmt*nper = 0
Examples
If you only had $150/month to pay towards the loan, how long would it take to pay-off a loan of $8,000 at 7%
annual interest?
Notes
The rate of interest is computed by iteratively solving the (non-linear) equation:
for rate.
References
Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Applica-
tions (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-
Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA,
USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-
formula OpenDocument-formula-20090508.odt
numpy.lib.arraysetops
Module with a number of other functions for performing set operations on arrays.
Examples
Return the indices of the original array that give the unique values:
in1d(ar1, ar2[, assume_unique]) Test whether each element of a 1D array is also present in a second
array.
intersect1d(ar1, ar2[, Find the intersection of two arrays.
assume_unique])
setdiff1d(ar1, ar2[, assume_unique]) Find the set difference of two arrays.
setxor1d(ar1, ar2[, assume_unique]) Find the set exclusive-or of two arrays.
union1d(ar1, ar2) Find the union of two arrays.
numpy.lib.arraysetops
Module with a number of other functions for performing set operations on arrays.
Notes
in1d can be considered as an element-wise function version of the python keyword in, for 1D sequences.
in1d(a, b) is roughly equivalent to np.array([item in b for item in a]). New in version
1.4.0.
Examples
See Also:
numpy.lib.arraysetops
Module with a number of other functions for performing set operations on arrays.
Examples
numpy.lib.arraysetops
Module with a number of other functions for performing set operations on arrays.
Examples
Returns
xor : ndarray
Sorted 1D array of unique values that are in only one of the input arrays.
Examples
union1d(ar1, ar2)
Find the union of two arrays.
Return the unique, sorted array of values that are in either of the two input arrays.
Parameters
ar1, ar2 : array_like
Input arrays. They are flattened if they are not already 1D.
Returns
union : ndarray
Unique, sorted union of the input arrays.
See Also:
numpy.lib.arraysetops
Module with a number of other functions for performing set operations on arrays.
Examples
Returns
out : array
The triangular window, normalized to one (the value one appears only if the number of
samples is odd), with the first and last samples equal to zero.
See Also:
blackman, hamming, hanning, kaiser
Notes
The Bartlett window is defined as
2 M 1 M 1
w(n) = n
M 1 2 2
Most references to the Bartlett window come from the signal processing literature, where it is used as one of
many windowing functions for smoothing values. Note that convolution with this window produces linear in-
terpolation. It is also known as an apodization (which meansremoving the foot, i.e. smoothing discontinuities
at the beginning and end of the sampled signal) or tapering function. The fourier transform of the Bartlett is the
product of two sinc functions. Note the excellent discussion in Kanasewich.
References
[R18], [R19], [R20], [R21], [R22]
Examples
>>> np.bartlett(12)
array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273,
0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636,
0.18181818, 0. ])
Plot the window and its frequency response (requires SciPy and matplotlib):
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
Bartlett window
1.0
0.8
0.6
Amplitude
0.4
0.2
0.0
0 10 20 30 40 50
Sample
20
Magnitude [dB]
40
60
80
100
0.4 0.2 0.0 0.2 0.4
Normalized frequency [cycles per sample]
blackman(M)
Return the Blackman window.
The Blackman window is a taper formed by using the the first three terms of a summation of cosines. It was
designed to have close to the minimal leakage possible. It is close to optimal, only slightly worse than a Kaiser
window.
Parameters
M : int
Number of points in the output window. If zero or less, an empty array is returned.
Returns
out : array
The window, normalized to one (the value one appears only if the number of samples is
odd).
See Also:
bartlett, hamming, hanning, kaiser
Notes
The Blackman window is defined as
Most references to the Blackman window come from the signal processing literature, where it is used as one of
many windowing functions for smoothing values. It is also known as an apodization (which means removing
the foot, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function. It
is known as a near optimal tapering function, almost as good (by some measures) as the kaiser window.
References
[R24], [R25], [R26]
Examples
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Blackman window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis(tight)
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
Blackman window
1.0
0.8
0.6
Amplitude
0.4
0.2
0.0
0.2
0 10 20 30 40 50
Sample
20
Magnitude [dB]
40
60
80
100
0.4 0.2 0.0 0.2 0.4
Normalized frequency [cycles per sample]
hamming(M)
Return the Hamming window.
The Hamming window is a taper formed by using a weighted cosine.
Parameters
M : int
Number of points in the output window. If zero or less, an empty array is returned.
Returns
out : ndarray
The window, normalized to one (the value one appears only if the number of samples is
odd).
See Also:
bartlett, blackman, hanning, kaiser
Notes
The Hamming window is defined as
2n
w(n) = 0.54 + 0.46cos 0nM 1
M 1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and is described in Blackman and
Tukey. It was recommended for smoothing the truncated autocovariance function in the time domain. Most
references to the Hamming window come from the signal processing literature, where it is used as one of many
windowing functions for smoothing values. It is also known as an apodization (which means removing the
foot, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
References
[R30], [R31], [R32], [R33]
Examples
>>> np.hamming(12)
array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594,
0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909,
0.15302337, 0.08 ])
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(mag)
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Hamming window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis(tight)
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
Hamming window
1.0
0.8
0.6
Amplitude
0.4
0.2
0.0
0 10 20 30 40 50
Sample
20
Magnitude [dB]
40
60
80
100
0.4 0.2 0.0 0.2 0.4
Normalized frequency [cycles per sample]
hanning(M)
Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
M : int
Number of points in the output window. If zero or less, an empty array is returned.
Returns
out : ndarray, shape(M,)
The window, normalized to one (the value one appears only if M is odd).
See Also:
bartlett, blackman, hamming, kaiser
Notes
The Hanning window is defined as
2n
w(n) = 0.5 0.5cos 0nM 1
M 1
The Hanning was named for Julius van Hann, an Austrian meterologist. It is also known as the Cosine Bell.
Some authors prefer that it be called a Hann window, to help avoid confusion with the very similar Hamming
window.
Most references to the Hanning window come from the signal processing literature, where it is used as one of
many windowing functions for smoothing values. It is also known as an apodization (which means removing
the foot, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
References
[R34], [R35], [R36], [R37]
Examples
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = np.linspace(-0.5,0.5,len(A))
>>> response = 20*np.log10(mag)
>>> response = np.clip(response,-100,100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of the Hann window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis(tight)
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
Hann window
1.0
0.8
0.6
Amplitude
0.4
0.2
0.0
0 10 20 30 40 50
Sample
20
Magnitude [dB]
40
60
80
100
0.4 0.2 0.0 0.2 0.4
Normalized frequency [cycles per sample]
kaiser(M, beta)
Return the Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
Parameters
M : int
Number of points in the output window. If zero or less, an empty array is returned.
beta : float
Shape parameter for window.
Returns
out : array
The window, normalized to one (the value one appears only if the number of samples is
odd).
See Also:
bartlett, blackman, hamming, hanning
Notes
The Kaiser window is defined as
s !
4n2
w(n) = I0 1 /I0 ()
(M 1)2
with
M 1 M 1
n ,
2 2
or Slepian window, which is the transform which maximizes the energy in the main lobe of the window relative
to total energy.
The Kaiser can approximate many other windows by varying the beta parameter.
beta Window shape
0 Rectangular
5 Similar to a Hamming
6 Similar to a Hanning
8.6 Similar to a Blackman
A beta value of 14 is probably a good starting point. Note that as beta gets large, the window narrows, and so
the number of samples needs to be large enough to sample the increasingly narrow spike, otherwise nans will
get returned.
Most references to the Kaiser window come from the signal processing literature, where it is used as one of
many windowing functions for smoothing values. It is also known as an apodization (which means removing
the foot, i.e. smoothing discontinuities at the beginning and end of the sampled signal) or tapering function.
References
[R43], [R44], [R45]
Examples
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = abs(fftshift(A))
>>> freq = linspace(-0.5,0.5,len(A))
>>> response = 20*log10(mag)
>>> response = clip(response,-100,100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
Kaiser window
1.0
0.8
0.6
Amplitude
0.4
0.2
0.0
0 10 20 30 40 50
Sample
20
Magnitude [dB]
40
60
80
100
0.4 0.2 0.0 0.2 0.4
Normalized frequency [cycles per sample]
seterr([all, divide, over, under, invalid]) Set how floating-point errors are handled.
geterr() Get the current way of handling floating-point errors.
seterrcall(func) Set the floating-point error callback function or log object.
geterrcall() Return the current callback function used on floating-point errors.
errstate(**kwargs) Context manager for floating-point error handling.
seterr(all=None, divide=None, over=None, under=None, invalid=None)
Set how floating-point errors are handled.
Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by
these settings.
Parameters
all : {ignore, warn, raise, call, print, log}, optional
Set treatment for all types of floating-point errors at once:
ignore: Take no action when the exception occurs.
warn: Print a RuntimeWarning (via the Python warnings module).
raise: Raise a FloatingPointError.
call: Call a function specified using the seterrcall function.
print: Print a warning directly to stdout.
log: Record error in a Log object specified by seterrcall.
The default is not to change the current behavior.
divide : {ignore, warn, raise, call, print, log}, optional
Treatment for division by zero.
over : {ignore, warn, raise, call, print, log}, optional
Treatment for floating-point overflow.
under : {ignore, warn, raise, call, print, log}, optional
Treatment for floating-point underflow.
invalid : {ignore, warn, raise, call, print, log}, optional
Treatment for invalid floating-point operation.
Returns
old_settings : dict
Dictionary containing the old settings.
See Also:
seterrcall
Set a callback function for the call mode.
geterr, geterrcall
Notes
The floating-point exceptions are defined in the IEEE 754 standard [1]:
Division by zero: infinite result obtained from finite numbers.
Overflow: result too large to be expressed.
Underflow: result so close to zero that some precision was lost.
Invalid operation: result is not an expressible number, typically indicates that a NaN was produced.
Examples
geterr()
Get the current way of handling floating-point errors.
Returns
res : dict
A dictionary with keys divide, over, under, and invalid, whose values are from
the strings ignore, print, log, warn, raise, and call. The keys represent pos-
sible floating-point exceptions, and the values define how these exceptions are handled.
See Also:
geterrcall, seterr, seterrcall
Notes
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.
Examples
seterrcall(func)
Set the floating-point error callback function or log object.
There are two ways to capture floating-point error messages. The first is to set the error-handler to call, using
seterr. Then, set the function to call using this function.
The second is to set the error-handler to log, using seterr. Floating-point errors then trigger a call to the write
method of the provided object.
Parameters
func : callable f(err, flag) or object with write method
Function to call upon floating-point errors (call-mode) or object whose write method
is used to log such message (log-mode).
The call function takes two arguments. The first is the type of error (one of divide,
over, under, or invalid), and the second is the status flag. The flag is a byte, whose
least-significant bits indicate the status:
Examples
Callback upon error:
>>> np.seterrcall(saved_handler)
<function err_handler at 0x...>
>>> np.seterr(**save_err)
{over: call, divide: call, invalid: call, under: call}
>>> np.seterrcall(saved_handler)
<__main__.Log object at 0x...>
>>> np.seterr(**save_err)
{over: log, divide: log, invalid: log, under: log}
geterrcall()
Return the current callback function used on floating-point errors.
When the error handling for a floating-point error (one of divide, over, under, or invalid) is set to call
or log, the function that is called or the log instance that is written to is returned by geterrcall. This function
or log instance has been set with seterrcall.
Returns
errobj : callable, log instance or None
The current error handler. If no handler was set through seterrcall, None is returned.
See Also:
seterrcall, seterr, geterr
Notes
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.
Examples
class errstate(**kwargs)
Context manager for floating-point error handling.
Using an instance of errstate as a context manager allows statements in that context to execute with a known
error handling behavior. Upon entering the context the error handling is set with seterr and seterrcall, and upon
exiting it is reset to what it was before.
Parameters
kwargs : {divide, over, under, invalid}
Keyword arguments. The valid keywords are the possible floating-point exceptions.
Each keyword should have a string value that defines the treatment for the particular
error. Possible values are {ignore, warn, raise, call, print, log}.
See Also:
seterr, geterr, seterrcall, geterrcall
Notes
The with statement was introduced in Python 2.5, and can only be used there by importing it: from
__future__ import with_statement. In earlier Python versions the with statement is not avail-
able.
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.
Examples
>>> np.arange(3) / 0.
array([ NaN, Inf, Inf])
>>> with np.errstate(divide=warn):
... np.arange(3) / 0.
...
__main__:2: RuntimeWarning: divide by zero encountered in divide
array([ NaN, Inf, Inf])
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid=raise):
... np.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
Outside the context the error handling behavior has not changed:
>>> np.geterr()
{over: ignore, divide: ignore, invalid: ignore,
under: ignore}
Notes
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.
Examples
>>> np.geterr()
{over: warn, divide: print, invalid: ignore, under: ignore}
>>> np.geterrcall() is err_handler
True
geterrobj()
Return the current object that defines floating-point error handling.
The error object contains all information that defines the error handling behavior in Numpy. geterrobj is used
internally by the other functions that get and set error handling behavior (geterr, seterr, geterrcall, seterrcall).
Returns
errobj : list
The error object, a list containing three elements: [internal numpy buffer size, error
mask, error callback function].
The error mask is a single integer that holds the treatment information on all four float-
ing point errors. The information for each error type is contained in three bits of the
integer. If we print it in base 8, we can see what treatment is set for invalid, under,
over, and divide (in that order). The printed string can be interpreted with
0 : ignore
1 : warn
2 : raise
3 : call
4 : print
5 : log
See Also:
seterrobj, seterr, geterr, seterrcall, geterrcall, getbufsize, setbufsize
Notes
For complete documentation of the types of floating-point exceptions and treatment options, see seterr.
Examples
invalid=print)
>>> np.base_repr(np.geterrobj()[1], 8)
4351
3.20.1 Constants
3.20.2 Creation
Parameters
data : array_like
Input data.
mask : sequence, optional
Mask. Must be convertible to an array of booleans with the same shape as data. True
indicates a masked (i.e. invalid) data.
dtype : dtype, optional
Data type of the output. If dtype is None, the type of the data argument (data.dtype)
is used. If dtype is not None and different from data.dtype, a copy is performed.
copy : bool, optional
Whether to copy the input data (True), or to use a reference instead. Default is False.
subok : bool, optional
Whether to return a subclass of MaskedArray if possible (True) or a plain MaskedArray.
Default is True.
ndmin : int, optional
Minimum number of dimensions. Default is 0.
fill_value : scalar, optional
Value used to fill in the masked values when necessary. If None, a default based on the
data-type is used.
keep_mask : bool, optional
Whether to combine mask with the mask of the input data, if any (True), or to use only
mask for the output (False). Default is True.
hard_mask : bool, optional
Whether to use a hard mask or not. With a hard mask, masked values cannot be un-
masked. Default is False.
shrink : bool, optional
Whether to force compression of an empty mask. Default is True.
copy
copy a.copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
frombuffer
Interpret a buffer as a 1-dimensional array.
Parameters
buffer :
An object that exposes the buffer interface.
dtype : data-type, optional
Data type of the returned array.
count : int, optional
Number of items to read. -1 means all data in the buffer.
offset : int, optional
Start reading the buffer from this offset.
Notes
If the buffer has data that is not in machine byte-order, this should be specified as part of the data-type, e.g.:
>>> dt = np.dtype(int)
>>> dt = dt.newbyteorder(>)
>>> np.frombuffer(buf, dtype=dt)
The data of the resulting array will not be byteswapped, but will be interpreted correctly.
Examples
fromfunction
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value fn(x, y, z) at coordinate (x, y, z).
Parameters
function : callable
The function is called with N parameters, each of which represents the coordinates of
the array varying along a specific axis. For example, if shape were (2, 2), then the
parameters would be two arrays, [[0, 0], [1, 1]] and [[0, 1], [0, 1]].
function must be capable of operating on arrays, and should return a scalar value.
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of the coordinate arrays
passed to function.
dtype : data-type, optional
Data-type of the coordinate arrays passed to function. By default, dtype is float.
Returns
out : any
The result of the call to function is passed back directly. Therefore the type and shape
of out is completely determined by function.
See Also:
indices, meshgrid
Notes
Keywords other than shape and dtype are passed to function.
Examples
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
ma.empty(shape[, dtype, order]) Return a new array of given shape and type, without initializing entries.
ma.empty_like(a) Return a new array with the same shape and type as a given array.
ma.masked_all(shape[, dtype]) Empty masked array with all elements masked.
ma.masked_all_like(arr) Empty masked array with the properties of an existing array.
ma.ones(shape[, dtype, order]) Return a new array of given shape and type, filled with ones.
ma.zeros(shape[, dtype, order]) Return a new array of given shape and type, filled with zeros.
empty
Return a new array of given shape and type, without initializing entries.
Parameters
shape : int or tuple of int
Shape of the empty array
dtype : data-type, optional
Desired output data-type.
order : {C, F}, optional
Whether to store multi-dimensional data in C (row-major) or Fortran (column-major)
order in memory.
See Also:
empty_like, zeros, ones
Notes
empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster. On the other
hand, it requires the user to manually set all the values in the array, and should be used with caution.
Examples
empty_like
Return a new array with the same shape and type as a given array.
Parameters
a : array_like
The shape and data-type of a define the parameters of the returned array.
Returns
out : ndarray
Array of random data with the same shape and type as a.
See Also:
ones_like
Return an array of ones with shape and type of input.
zeros_like
Return an array of zeros with shape and type of input.
empty
Return a new uninitialized array.
ones
Return a new array setting values to one.
zeros
Return a new array setting values to zero.
Notes
This function does not initialize the returned array; to do that use zeros_like or ones_like instead. It may be
marginally faster than the functions that do set the array values.
Examples
masked_all_like
Empty masked array modelled on an existing array.
Examples
masked_all_like(arr)
Empty masked array with the properties of an existing array.
Return an empty masked array of the same shape and dtype as the array arr, where all the data are masked.
Parameters
arr : ndarray
An array describing the shape and dtype of the required MaskedArray.
Returns
a : MaskedArray
A masked array with all data masked.
Raises
AttributeError :
If arr doesnt have a shape attribute (i.e. not an ndarray)
See Also:
masked_all
Empty masked array with all elements masked.
Examples
>>> arr.dtype
dtype(float32)
>>> ma.masked_all_like(arr).dtype
dtype(float32)
ones
Return a new array of given shape and type, filled with ones.
Please refer to the documentation for zeros.
See Also:
zeros
Examples
>>> np.ones(5)
array([ 1., 1., 1., 1., 1.])
>>> s = (2,2)
>>> np.ones(s)
array([[ 1., 1.],
[ 1., 1.]])
zeros
Return a new array of given shape and type, filled with zeros.
Parameters
shape : int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.
dtype : data-type, optional
The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64.
order : {C, F}, optional
Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-
wise) order in memory.
Returns
out : ndarray
Array of zeros with the given shape, dtype, and order.
See Also:
zeros_like
Return an array of zeros with shape and type of input.
ones_like
Return an array of ones with shape and type of input.
empty_like
Return an empty array with shape and type of input.
ones
Return a new array setting values to one.
empty
Return a new uninitialized array.
Examples
>>> np.zeros(5)
array([ 0., 0., 0., 0., 0.])
>>> s = (2,2)
>>> np.zeros(s)
array([[ 0., 0.],
[ 0., 0.]])
all
Check if all of the elements of a are true.
Performs a logical_and over the given axis and returns the result. Masked values are considered as True
during computation. For convenience, the output array is masked where ALL the values along the current axis
are masked: if the output would have been a scalar and that all the values are masked, then the output is masked.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
all
equivalent function
Examples
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
any
Check if any of the elements of a are true.
Performs a logical_or over the given axis and returns the result. Masked values are considered as False during
computation.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array and return a
scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
any
equivalent function
count(a, axis=None)
Count the non-masked elements of the array along the given axis.
Parameters
axis : int, optional
Axis along which to count the non-masked elements. If axis is None, all non-masked
elements are counted.
Returns
result : int or ndarray
If axis is None, an integer count is returned. When axis is not None, an array with shape
determined by the lengths of the remaining axes, is returned.
See Also:
count_masked
Count masked elements in array or along a given axis.
Examples
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
count_masked(arr, axis=None)
Count the number of masked elements along the given axis.
Parameters
arr : array_like
An array with (possibly) masked elements.
axis : int, optional
Axis along which to count. If None (default), a flattened version of the array is used.
Returns
count : int, ndarray
The total number of masked elements (axis=None) or the number of masked elements
along each slice of the given axis.
See Also:
MaskedArray.count
Count non-masked elements.
Examples
getmask(a)
Return the mask of a masked array, or nomask.
Return the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask, else return nomask. To
guarantee a full array of booleans of the same shape as a, use getmaskarray.
Parameters
a : array_like
Input MaskedArray for which the mask is required.
See Also:
getdata
Return the data of a masked array as an ndarray.
getmaskarray
Return the mask of a masked array, or full array of False.
Examples
>>> ma.getmask(a)
array([[False, True],
[False, False]], dtype=bool)
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
getmaskarray(arr)
Return the mask of a masked array, or full boolean array of False.
Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask, else return a full
boolean array of False of the same shape as arr.
Parameters
arr : array_like
Input MaskedArray for which the mask is required.
See Also:
getmask
Return the mask of a masked array, or nomask.
getdata
Return the data of a masked array as an ndarray.
Examples
>>> ma.getmaskarray(a)
array([[False, True],
[False, False]], dtype=bool)
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> >ma.getmaskarray(b)
array([[False, False],
[False, False]], dtype=bool)
getdata(a, subok=True)
Return the data of a masked array as an ndarray.
Return the data of a (if any) as an ndarray if a is a MaskedArray, else return a as a ndarray or subclass
(depending on subok) if not.
Parameters
a : array_like
Input MaskedArray, alternatively a ndarray or a subclass thereof.
subok : bool
Whether to force the output to be a pure ndarray (False) or to return a subclass of ndarray
if appropriate (True, default).
See Also:
getmask
Return the mask of a masked array, or nomask.
getmaskarray
Return the mask of a masked array, or full array of False.
Examples
>>> a.data
array([[1, 2],
[3, 4]])
nonzero
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[a.nonzero()]
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero element.
Parameters
None :
Returns
tuple_of_arrays : tuple
Indices of elements that are non-zero.
See Also:
numpy.nonzero
Function operating on ndarrays.
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
[0.0 -- 0.0]
[0.0 0.0 1.0]],
mask =
[[False False False]
[False True False]
[False False False]],
fill_value=1e+20)
>>> x.nonzero()
(array([0, 2]), array([0, 2]))
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(data =
[[False False False]
[ True True True]
[ True True True]],
mask =
False,
fill_value=999999)
>>> ma.nonzero(a > 3)
(array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
shape(obj)
Return the shape of an array.
Parameters
a : array_like
Input array.
Returns
shape : tuple of ints
The elements of the shape tuple give the lengths of the corresponding array dimensions.
See Also:
alen
ndarray.shape
Equivalent array method.
Examples
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
size(obj, axis=None)
Return the number of elements along a given axis.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give the total number of ele-
ments.
Returns
element_count : int
Number of elements along the specified axis.
See Also:
shape
dimensions of array
ndarray.shape
dimensions of array
ndarray.size
number of elements in array
Examples
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
data
mask
Mask
recordmask
all(axis=None, out=None)
Check if all of the elements of a are true.
Performs a logical_and over the given axis and returns the result. Masked values are considered as True
during computation. For convenience, the output array is masked where ALL the values along the current axis
are masked: if the output would have been a scalar and that all the values are masked, then the output is masked.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
all
equivalent function
Examples
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
any(axis=None, out=None)
Check if any of the elements of a are true.
Performs a logical_or over the given axis and returns the result. Masked values are considered as False during
computation.
Parameters
axis : {None, integer}
Axis to perform the operation over. If None, perform over flattened array and return a
scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
See Also:
any
equivalent function
count(axis=None)
Count the non-masked elements of the array along the given axis.
Parameters
axis : int, optional
Axis along which to count the non-masked elements. If axis is None, all non-masked
elements are counted.
Returns
result : int or ndarray
If axis is None, an integer count is returned. When axis is not None, an array with shape
determined by the lengths of the remaining axes, is returned.
See Also:
count_masked
Count masked elements in array or along a given axis.
Examples
>>> a.count(axis=0)
array([1, 1, 1])
>>> a.count(axis=1)
array([3, 0])
nonzero()
Return the indices of unmasked elements that are not zero.
Returns a tuple of arrays, one for each dimension, containing the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained with:
a[a.nonzero()]
np.transpose(a.nonzero())
The result of this is always a 2d array, with a row for each non-zero element.
Parameters
None :
Returns
tuple_of_arrays : tuple
numpy.nonzero
Function operating on ndarrays.
flatnonzero
Return indices that are non-zero in the flattened version of the input array.
ndarray.nonzero
Equivalent ndarray method.
Examples
>>> np.transpose(x.nonzero())
array([[0, 0],
[2, 2]])
A common use for nonzero is to find the indices of an array, where a condition is True. Given an array a, the
condition a > 3 is a boolean array and since False is interpreted as 0, ma.nonzero(a > 3) yields the indices of the
a where the condition is true.
>>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
>>> a > 3
masked_array(data =
[[False False False]
shape(obj)
Return the shape of an array.
Parameters
a : array_like
Input array.
Returns
shape : tuple of ints
The elements of the shape tuple give the lengths of the corresponding array dimensions.
See Also:
alen
ndarray.shape
Equivalent array method.
Examples
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()
size(obj, axis=None)
Return the number of elements along a given axis.
Parameters
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give the total number of ele-
ments.
Returns
element_count : int
Number of elements along the specified axis.
See Also:
shape
dimensions of array
ndarray.shape
dimensions of array
ndarray.size
number of elements in array
Examples
>>> a = np.array([[1,2,3],[4,5,6]])
>>> np.size(a)
6
>>> np.size(a,1)
3
>>> np.size(a,0)
2
Examples
MaskedArray.reshape
equivalent function
resize(x, new_shape)
Return a new masked array with the specified size and shape.
This is the masked equivalent of the numpy.resize function. The new array is filled with repeated copies of
x (in the order that the data are stored in memory). If x is masked, the new array will be masked, and the new
mask will be a repetition of the old one.
See Also:
numpy.resize
Equivalent function in the top level NumPy module.
Examples
flatten(order=C)
Return a copy of the array collapsed into one dimension.
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is
C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
ravel()
Returns a 1D version of self, as a view.
Returns
MaskedArray :
Output view is of shape (self.size,) (or
(np.ma.product(self.shape),)).
Examples
[-- 5 --]
[7 -- 9]]
>>> print x.ravel()
[1 -- 3 -- 5 -- 7 -- 9]
reshape(*s, **kwargs)
Give a new shape to the array without changing its data.
Returns a masked array containing the same data, but with a new shape. The result is a view on the original
array; if this is not possible, a ValueError is raised.
Parameters
shape : int or tuple of ints
The new shape should be compatible with the original shape. If an integer is supplied,
then the result will be a 1-D array of that length.
order : {C, F}, optional
Determines whether the array data should be viewed as in C (row-major) or FORTRAN
(column-major) order.
Returns
reshaped_array : array
A new view on the array.
See Also:
reshape
Equivalent function in the masked array module.
numpy.ndarray.reshape
Equivalent method on ndarray object.
numpy.reshape
Equivalent function in the NumPy module.
Notes
The reshaping operation cannot guarantee that a copy will not be made, to modify the shape in place, use
a.shape = s
Examples
This method is difficult to implement safely and may be deprecated in future releases of NumPy.
Modifying axes
ma.swapaxes swapaxes
ma.transpose(a[, axes]) Permute the dimensions of an array.
ma.MaskedArray.swapaxes(axis1, axis2) Return a view of the array with axis1 and axis2 interchanged.
ma.MaskedArray.transpose(*axes) Returns a view of the array with axes transposed.
swapaxes
swapaxes a.swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
transpose(a, axes=None)
Permute the dimensions of an array.
This function is exactly equivalent to numpy.transpose.
See Also:
numpy.transpose
Equivalent function in top-level NumPy module.
Examples
swapaxes(axis1, axis2)
Return a view of the array with axis1 and axis2 interchanged.
Refer to numpy.swapaxes for full documentation.
See Also:
numpy.swapaxes
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a ma-
trix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order in-
dicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1],
... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1],
i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s j-th
axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
Examples
>>> np.atleast_1d(1.0)
array([ 1.])
>>> x = np.arange(9.0).reshape(3,3)
>>> np.atleast_1d(x)
array([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.]])
>>> np.atleast_1d(x) is x
True
atleast_2d(*arys)
View inputs as arrays with at least two dimensions.
Parameters
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays
that already have two or more dimensions are preserved.
Returns
res, res2, ... : ndarray
An array, or tuple of arrays, each with a.ndim >= 2. Copies are avoided where
possible, and views with two or more dimensions are returned.
See Also:
atleast_1d, atleast_3d
Examples
>>> np.atleast_2d(3.0)
array([[ 3.]])
>>> x = np.arange(3.0)
>>> np.atleast_2d(x)
array([[ 0., 1., 2.]])
>>> np.atleast_2d(x).base is x
True
atleast_3d(*arys)
View inputs as arrays with at least three dimensions.
Parameters
array1, array2, ... : array_like
One or more array-like sequences. Non-array inputs are converted to arrays. Arrays
that already have three or more dimensions are preserved.
Returns
res1, res2, ... : ndarray
An array, or tuple of arrays, each with a.ndim >= 3. Copies are avoided where
possible, and views with three or more dimensions are returned. For example, a 1-D
array of shape N becomes a view of shape (1, N, 1). A 2-D array of shape (M, N)
becomes a view of shape (M, N, 1).
See Also:
atleast_1d, atleast_2d
Examples
>>> np.atleast_3d(3.0)
array([[[ 3.]]])
>>> x = np.arange(3.0)
>>> np.atleast_3d(x).shape
(1, 3, 1)
>>> x = np.arange(12.0).reshape(4,3)
>>> np.atleast_3d(x).shape
(4, 3, 1)
>>> np.atleast_3d(x).base is x
True
expand_dims(x, axis)
Expand the shape of an array.
Expands the shape of the array by including a new axis before the one specified by the axis parameter. This
function behaves the same as numpy.expand_dims but preserves masked elements.
See Also:
numpy.expand_dims
Equivalent function in top-level NumPy module.
Examples
The same result can be achieved using slicing syntax with np.newaxis.
>>> x[np.newaxis, :]
masked_array(data =
[[1 -- 4]],
mask =
[[False True False]],
fill_value = 999999)
squeeze(a)
Remove single-dimensional entries from the shape of an array.
Parameters
a : array_like
Input data.
Returns
squeezed : ndarray
The input array, but with with all dimensions of length 1 removed. Whenever possible,
a view on a is returned.
Examples
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
column_stack
Parameters
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
stacked : 2-D array
The array formed by stacking the given arrays.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
concatenate(arrays, axis=0)
Concatenate a sequence of arrays along the given axis.
Parameters
arrays : sequence of array_like
The arrays must have the same shape, except in the dimension corresponding to axis
(the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
result : MaskedArray
The concatenated array with any masked entries preserved.
See Also:
numpy.concatenate
Equivalent function in the top-level NumPy module.
Examples
dstack
Parameters
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all but the third axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack along first axis.
hstack
Stack along second axis.
concatenate
Join arrays.
dsplit
Split array along third axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
hstack
Parameters
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third axis).
concatenate
Join a sequence of arrays together.
hsplit
Split array along second axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
hsplit
split
Split an array into multiple sub-arrays of equal size.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> x = np.arange(16.0).reshape(4, 4)
>>> x
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]])
>>> np.hsplit(x, 2)
[array([[ 0., 1.],
[ 4., 5.],
[ 8., 9.],
[ 12., 13.]]),
array([[ 2., 3.],
[ 6., 7.],
[ 10., 11.],
[ 14., 15.]])]
>>> np.hsplit(x, np.array([3, 6]))
[array([[ 0., 1., 2.],
With a higher dimensional array the split is still along the second axis.
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[ 0., 1.],
[ 2., 3.]],
[[ 4., 5.],
[ 6., 7.]]])
>>> np.hsplit(x, 2)
[array([[[ 0., 1.]],
[[ 4., 5.]]]),
array([[[ 2., 3.]],
[[ 6., 7.]]])]
mr_
Translate slice objects to concatenation along the first axis.
This is the masked array version of lib.index_tricks.RClass.
See Also:
lib.index_tricks.RClass
Examples
row_stack
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
vstack
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
Joining arrays
Parameters
tup : sequence of 1-D or 2-D arrays.
Arrays to stack. All of them must have the same first dimension.
Returns
stacked : 2-D array
The array formed by stacking the given arrays.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.column_stack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
concatenate(arrays, axis=0)
Concatenate a sequence of arrays along the given axis.
Parameters
arrays : sequence of array_like
The arrays must have the same shape, except in the dimension corresponding to axis
(the first, by default).
axis : int, optional
The axis along which the arrays will be joined. Default is 0.
Returns
result : MaskedArray
The concatenated array with any masked entries preserved.
See Also:
numpy.concatenate
Equivalent function in the top-level NumPy module.
Examples
dstack
Parameters
tup : sequence of arrays
Arrays to stack. All of them must have the same shape along all but the third axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack along first axis.
hstack
Stack along second axis.
concatenate
Join arrays.
dsplit
Split array along third axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.dstack((a,b))
array([[[1, 2],
[2, 3],
[3, 4]]])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.dstack((a,b))
array([[[1, 2]],
[[2, 3]],
[[3, 4]]])
hstack
Parameters
tup : sequence of ndarrays
All arrays must have the same shape along all but the second axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
vstack
Stack arrays in sequence vertically (row wise).
dstack
Stack arrays in sequence depth wise (along third axis).
concatenate
Join a sequence of arrays together.
hsplit
Split array along second axis.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
>>> a = np.array((1,2,3))
>>> b = np.array((2,3,4))
>>> np.hstack((a,b))
array([1, 2, 3, 2, 3, 4])
>>> a = np.array([[1],[2],[3]])
>>> b = np.array([[2],[3],[4]])
>>> np.hstack((a,b))
array([[1, 2],
[2, 3],
[3, 4]])
vstack
Parameters
tup : sequence of ndarrays
Tuple containing arrays to be stacked. The arrays must have the same shape along all
but the first axis.
Returns
stacked : ndarray
The array formed by stacking the given arrays.
See Also:
hstack
Stack arrays in sequence horizontally (column wise).
dstack
Stack arrays in sequence depth wise (along third dimension).
concatenate
Join a sequence of arrays together.
vsplit
Split array into a list of multiple sub-arrays vertically.
Notes
The function is applied to both the _data and the _mask, if any.
Examples
Creating a mask
ma.make_mask(m[, copy, shrink, flag, dtype]) Create a boolean mask from an array.
ma.make_mask_none(newshape[, dtype]) Return a boolean mask of the given shape, filled with False.
ma.mask_or(m1, m2[, copy, shrink]) Combine two masks with the logical_or operator.
ma.make_mask_descr(ndtype) Construct a dtype description list from a given dtype.
make_mask(m, copy=False, shrink=True, flag=None, dtype=<type numpy.bool_>)
Create a boolean mask from an array.
Return m as a boolean mask, creating a copy if necessary or requested. The function can accept any sequence
that is convertible to integers, or nomask. Does not require that contents must be 0s and 1s, values of 0 are
interepreted as False, everything else as True.
Parameters
m : array_like
Potential mask.
copy : bool, optional
Whether to return a copy of m (True) or m itself (False).
shrink : bool, optional
Whether to shrink m to nomask if all its values are False.
flag : bool, optional
Deprecated equivalent of shrink.
Examples
>>> m = np.zeros(4)
>>> m
array([ 0., 0., 0., 0.])
>>> ma.make_mask(m)
False
>>> ma.make_mask(m, shrink=False)
array([False, False, False, False], dtype=bool)
>>> m = [1, 0, 1, 1]
>>> n = [0, 1, 0, 0]
>>> arr = []
>>> for man, mouse in zip(m, n):
... arr.append((man, mouse))
>>> arr
[(1, 0), (0, 1), (1, 0), (1, 0)]
>>> dtype = np.dtype({names:[man, mouse],
formats:[np.int, np.int]})
>>> arr = np.array(arr, dtype=dtype)
>>> arr
array([(1, 0), (0, 1), (1, 0), (1, 0)],
dtype=[(man, <i4), (mouse, <i4)])
>>> ma.make_mask(arr, dtype=dtype)
array([(True, False), (False, True), (True, False), (True, False)],
dtype=[(man, |b1), (mouse, |b1)])
make_mask_none(newshape, dtype=None)
Return a boolean mask of the given shape, filled with False.
This function returns a boolean ndarray with all entries False, that can be used in common mask manipulations.
If a complex dtype is specified, the type of each field is converted to a boolean type.
Parameters
newshape : tuple
A tuple indicating the shape of the mask.
dtype: {None, dtype}, optional :
If None, use a MaskType instance. Otherwise, use a new datatype with the same fields
as dtype, converted to boolean types.
Returns
result : ndarray
An ndarray of appropriate shape and dtype, filled with False.
See Also:
make_mask
Create a boolean mask from an array.
make_mask_descr
Construct a dtype description list from a given dtype.
Examples
Raises
ValueError :
If m1 and m2 have different flexible dtypes.
Examples
make_mask_descr(ndtype)
Construct a dtype description list from a given dtype.
Returns a new dtype object, with the type of all fields in ndtype to a boolean type. Field names are not altered.
Parameters
ndtype : dtype
The dtype to convert.
Returns
result : dtype
A dtype that looks like ndtype, the type of all fields is boolean.
Examples
Accessing a mask
getdata
Return the data of a masked array as an ndarray.
getmaskarray
Return the mask of a masked array, or full array of False.
Examples
>>> a.mask
array([[False, True],
[False, False]], dtype=bool)
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True
getmaskarray(arr)
Return the mask of a masked array, or full boolean array of False.
Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask, else return a full
boolean array of False of the same shape as arr.
Parameters
arr : array_like
Input MaskedArray for which the mask is required.
See Also:
getmask
Return the mask of a masked array, or nomask.
getdata
Return the data of a masked array as an ndarray.
Examples
>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
[[1 2]
[3 4]],
mask =
False,
fill_value=999999)
>>> >ma.getmaskarray(b)
array([[False, False],
[False, False]], dtype=bool)
mask
Mask
ma.flatnotmasked_contiguous(a) Find contiguous unmasked data in a masked array along the given axis.
ma.flatnotmasked_edges(a) Find the indices of the first and last unmasked values.
ma.notmasked_contiguous(a[, axis]) Find contiguous unmasked data in a masked array along the given axis.
ma.notmasked_edges(a[, axis]) Find the indices of the first and last unmasked values along an axis.
flatnotmasked_contiguous(a)
Find contiguous unmasked data in a masked array along the given axis.
Parameters
a : narray
The input array.
Returns
slice_list : list
A sorted sequence of slices (start index, end index).
See Also:
flatnotmasked_edges, notmasked_contiguous, notmasked_edges
Notes
Only accepts 2-D arrays at most.
Examples
>>> a = np.arange(10)
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> ma = np.ma.array(a, mask=mask)
>>> np.array(ma[~ma.mask])
array([3, 4, 6, 7, 8])
>>> np.ma.extras.flatnotmasked_contiguous(ma)
[slice(3, 4, None), slice(6, 8, None)]
>>> ma = np.ma.array(a, mask=np.ones_like(a))
>>> print np.ma.extras.flatnotmasked_edges(ma)
None
flatnotmasked_edges(a)
Find the indices of the first and last unmasked values.
Expects a 1-D MaskedArray, returns None if all values are masked.
Parameters
arr : array_like
Input 1-D MaskedArray
Returns
edges : ndarray or None
The indices of first and last non-masked value in the array. Returns None if all values
are masked.
See Also:
flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges
Notes
Only accepts 1-D arrays.
Examples
>>> a = np.arange(10)
>>> mask = (a < 3) | (a > 8) | (a == 5)
>>> flatnotmasked_edges(ma)
array([3, 8])
notmasked_contiguous(a, axis=None)
Find contiguous unmasked data in a masked array along the given axis.
Parameters
a : array_like
The input array.
axis : int, optional
Axis along which to perform the operation. If None (default), applies to a flattened
version of the array.
Returns
endpoints : list
A list of slices (start and end indexes) of unmasked indexes in the array.
See Also:
flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges
Notes
Only accepts 2-D arrays at most.
Examples
>>> np.ma.extras.notmasked_contiguous(ma)
[slice(0, 3, None), slice(6, 6, None)]
notmasked_edges(a, axis=None)
Find the indices of the first and last unmasked values along an axis.
If all values are masked, return None. Otherwise, return a list of two tuples, corresponding to the indices of the
first and last unmasked values respectively.
Parameters
a : array_like
The input array.
axis : int, optional
Axis along which to perform the operation. If None (default), applies to a flattened
version of the array.
Returns
edges : ndarray or list
An array of start and end indexes if there are any masked data in the array. If there are
no masked data in the array, edges is a list of the first and last index.
See Also:
flatnotmasked_contiguous, flatnotmasked_edges, notmasked_contiguous
Examples
>>> np.ma.extras.notmasked_edges(ma)
array([0, 6])
Modifying a mask
mask_rowcols
Mask rows and/or columns of a 2D array.
masked_where
Mask where a condition is met.
Examples
>>> a
masked_array(data =
[[0 0 0]
[0 -- 0]
[0 0 0]],
mask =
[[False False False]
[False True False]
[False False False]],
fill_value=999999)
>>> ma.mask_cols(a)
masked_array(data =
[[0 -- 0]
[0 -- 0]
[0 -- 0]],
mask =
[[False True False]
[False True False]
[False True False]],
fill_value=999999)
Examples
mask_rowcols(a, axis=None)
Mask rows and/or columns of a 2D array that contain masked values.
Mask whole rows and/or columns of a 2D array that contain masked values. The masking behavior is selected
using the axis parameter.
Parameters
a : array_like, MaskedArray
The array to mask. If not a MaskedArray instance (or if no array elements are masked).
The result is a MaskedArray with mask set to nomask (False). Must be a 2D array.
axis : int, optional
Axis along which to perform the operation. If None, applies to a flattened version of the
array.
Returns
a : MaskedArray
A modified version of the input array, masked depending on the value of the axis pa-
rameter.
Raises
NotImplementedError :
If input array a is not 2D.
See Also:
mask_rows
Mask rows of a 2D array that contain masked values.
mask_cols
Mask cols of a 2D array that contain masked values.
masked_where
Mask where a condition is met.
Notes
The input arrays mask is modified by this function.
Examples
mask_rows(a, axis=None)
Mask rows of a 2D array that contain masked values.
This function is a shortcut to mask_rowcols with axis equal to 0.
See Also:
mask_rowcols
Mask rows and/or columns of a 2D array.
masked_where
Mask where a condition is met.
Examples
harden_mask
Examples
unshare_mask()
Copy the mask and set the sharedmask flag to False.
Whether the mask is shared between masked arrays can be seen from the sharedmask property. unshare_mask
ensures the mask is not shared. A copy of the mask is only made if it was shared.
See Also:
sharedmask
ma.asarray(a[, dtype, order]) Convert the input to a masked array of the given data-type.
ma.asanyarray(a[, dtype]) Convert the input to a masked array, conserving subclasses.
ma.fix_invalid(a[, mask, copy, fill_value]) Return input with invalid data masked and replaced by a fill
value.
ma.masked_equal(x, value[, copy]) Mask an array where equal to a given value.
ma.masked_greater(x, value[, copy]) Mask an array where greater than a given value.
ma.masked_greater_equal(x, value[, Mask an array where greater than or equal to a given value.
copy])
ma.masked_inside(x, v1, v2[, copy]) Mask an array inside a given interval.
ma.masked_invalid(a[, copy]) Mask an array where invalid values occur (NaNs or infs).
ma.masked_less(x, value[, copy]) Mask an array where less than a given value.
ma.masked_less_equal(x, value[, copy]) Mask an array where less than or equal to a given value.
ma.masked_not_equal(x, value[, copy]) Mask an array where not equal to a given value.
ma.masked_object(x, value[, copy, shrink]) Mask the array x where the data are exactly equal to value.
ma.masked_outside(x, v1, v2[, copy]) Mask an array outside a given interval.
ma.masked_values(x, value[, rtol, atol, ...]) Mask using floating point equality.
ma.masked_where(condition, a[, copy]) Mask an array where a condition is met.
asarray(a, dtype=None, order=None)
Convert the input to a masked array of the given data-type.
No copy is performed if the input is already an ndarray. If a is a subclass of MaskedArray, a base class
MaskedArray is returned.
Parameters
a : array_like
Input data, in any form that can be converted to a masked array. This includes lists, lists
of tuples, tuples, tuples of tuples, tuples of lists, ndarrays and masked arrays.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {C, F}, optional
Whether to use row-major (C) or column-major (FORTRAN) memory representa-
tion. Default is C.
Returns
out : MaskedArray
Masked array interpretation of a.
See Also:
asanyarray
Similar to asarray, but conserves subclasses.
Examples
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asarray(x))
<class numpy.ma.core.MaskedArray>
asanyarray(a, dtype=None)
Convert the input to a masked array, conserving subclasses.
If a is a subclass of MaskedArray, its class is conserved. No copy is performed if the input is already an ndarray.
Parameters
a : array_like
Input data, in any form that can be converted to an array.
dtype : dtype, optional
By default, the data-type is inferred from the input data.
order : {C, F}, optional
Whether to use row-major (C) or column-major (FORTRAN) memory representa-
tion. Default is C.
Returns
out : MaskedArray
MaskedArray interpretation of a.
See Also:
asarray
Similar to asanyarray, but does not conserve subclass.
Examples
>>> x = np.arange(10.).reshape(2, 5)
>>> x
array([[ 0., 1., 2., 3., 4.],
[ 5., 6., 7., 8., 9.]])
>>> np.ma.asanyarray(x)
masked_array(data =
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]],
mask =
False,
fill_value = 1e+20)
>>> type(np.ma.asanyarray(x))
<class numpy.ma.core.MaskedArray>
Notes
A copy is performed by default.
Examples
masked_where
Mask where a condition is met.
masked_values
Mask using floating point equality.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
See Also:
masked_where
Mask where a condition is met.
Notes
The array x is prefilled with its filling value.
Examples
masked_invalid(a, copy=True)
Mask an array where invalid values occur (NaNs or infs).
This function is a shortcut to masked_where, with condition = ~(np.isfinite(a)). Any pre-existing mask is
conserved. Only applies to arrays with a dtype where NaNs or infs make sense (i.e. floating point types), but
accepts any array_like object.
See Also:
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
masked_where
Mask where a condition is met.
Examples
This function is similar to masked_values, but only suitable for object arrays: for floating point, use
masked_values instead.
Parameters
x : array_like
Array to mask
value : object
Comparison value
copy : {True, False}, optional
Whether to return a copy of x.
shrink : {True, False}, optional
Whether to collapse a mask full of False to nomask
Returns
result : MaskedArray
The result of masking x where equal to value.
See Also:
masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
masked_values
Mask using floating point equality.
Examples
>>> eat
masked_array(data = [cheese ham pineapple],
mask = False,
fill_value=?)
See Also:
masked_where
Mask where a condition is met.
Notes
The array x is prefilled with its filling value.
Examples
masked_where
Mask where a condition is met.
masked_equal
Mask where equal to a given value (integers).
Examples
For integers, the fill value will be different in general to the result of masked_equal.
>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> ma.masked_values(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=2)
>>> ma.masked_equal(x, 2)
masked_array(data = [0 1 -- 3 4],
mask = [False False True False False],
fill_value=999999)
masked_where(condition, a, copy=True)
Mask an array where a condition is met.
Return a as an array masked where condition is True. Any masked values of a or condition are also masked in
the output.
Parameters
condition : array_like
Masking condition. When condition tests floating point values for equality, consider
using masked_values instead.
a : array_like
Array to mask.
copy : bool
If True (default) make a copy of a in the result. If False modify a in place and return a
view.
Returns
result : MaskedArray
The result of masking a where condition is True.
See Also:
masked_values
Mask using floating point equality.
masked_equal
Mask where equal to a given value.
masked_not_equal
Mask where not equal to a given value.
masked_less_equal
Mask where less than or equal to a given value.
masked_greater_equal
Mask where greater than or equal to a given value.
masked_less
Mask where less than a given value.
masked_greater
Mask where greater than a given value.
masked_inside
Mask inside a given interval.
masked_outside
Mask outside a given interval.
masked_invalid
Mask invalid values (NaNs or infs).
Examples
>>> b = [a, b, c, d]
>>> ma.masked_where(a == 2, b)
masked_array(data = [a b -- d],
mask = [False False True False],
fill_value=N/A)
>>> a = np.arange(4)
>>> a = ma.masked_where(a == 2, a)
>>> a
masked_array(data = [0 1 -- 3],
mask = [False False True False],
fill_value=999999)
>>> b = np.arange(4)
>>> b = ma.masked_where(b == 0, b)
>>> b
masked_array(data = [-- 1 2 3],
mask = [ True False False False],
fill_value=999999)
>>> ma.masked_where(a == 3, b)
masked_array(data = [-- 1 -- --],
mask = [ True False True True],
fill_value=999999)
> to a ndarray
ma.compress_cols(a) Suppress whole columns of a 2-D array that contain masked values.
ma.compress_rowcols(x[, axis]) Suppress the rows and/or columns of a 2-D array that contain
ma.compress_rows(a) Suppress whole rows of a 2-D array that contain masked values.
ma.compressed(x) Return all the non-masked data as a 1-D array.
ma.filled(a[, fill_value]) Return input as an array with masked data replaced by a fill value.
ma.MaskedArray.compressed() Return all the non-masked data as a 1-D array.
ma.MaskedArray.filled([fill_value]) Return a copy of self, with masked values filled with a given value.
compress_cols(a)
Suppress whole columns of a 2-D array that contain masked values.
This is equivalent to np.ma.extras.compress_rowcols(a, 1), see extras.compress_rowcols for de-
tails.
See Also:
extras.compress_rowcols
compress_rowcols(x, axis=None)
Suppress the rows and/or columns of a 2-D array that contain masked values.
The suppression behavior is selected with the axis parameter.
If axis is None, both rows and columns are suppressed.
If axis is 0, only rows are suppressed.
If axis is 1 or -1, only columns are suppressed.
Parameters
axis : int, optional
Axis along which to perform the operation. Default is None.
Returns
compressed_array : ndarray
The compressed array.
Examples
>>> np.ma.extras.compress_rowcols(x)
array([[7, 8]])
>>> np.ma.extras.compress_rowcols(x, 0)
array([[6, 7, 8]])
>>> np.ma.extras.compress_rowcols(x, 1)
array([[1, 2],
[4, 5],
[7, 8]])
compress_rows(a)
Suppress whole rows of a 2-D array that contain masked values.
This is equivalent to np.ma.extras.compress_rowcols(a, 0), see extras.compress_rowcols for de-
tails.
See Also:
extras.compress_rowcols
compressed(x)
Return all the non-masked data as a 1-D array.
This function is equivalent to calling the compressed method of a MaskedArray, see MaskedArray.compressed
for details.
See Also:
MaskedArray.compressed
Equivalent method.
filled(a, fill_value=None)
Return input as an array with masked data replaced by a fill value.
If a is not a MaskedArray, a itself is returned. If a is a MaskedArray and fill_value is None, fill_value is set to
a.fill_value.
Parameters
a : MaskedArray or array_like
An input object.
fill_value : scalar, optional
Filling value. Default is None.
Returns
a : ndarray
The filled array.
See Also:
compressed
Examples
compressed()
Return all the non-masked data as a 1-D array.
Returns
data : ndarray
A new ndarray holding the non-masked data is returned.
Notes
The result is not a MaskedArray!
Examples
filled(fill_value=None)
Return a copy of self, with masked values filled with a given value.
Parameters
fill_value : scalar, optional
The value to use for invalid entries (None by default). If None, the fill_value attribute
of the array is used instead.
Notes
The result is not a MaskedArray!
Examples
Subclassing is preserved. This means that if the data part of the masked array is a matrix, filled returns a matrix:
Raises
NotImplementedError :
When tofile is called.
tolist(fill_value=None)
Return the data portion of the masked array as a hierarchical Python list.
Data items are converted to the nearest compatible Python type. Masked values are converted to fill_value. If
fill_value is None, the corresponding entries in the output list will be None.
Parameters
fill_value : scalar, optional
The value to use for invalid entries. Default is None.
Returns
result : list
The Python list representation of the masked array.
Examples
torecords()
Transforms a masked array into a flexible-type array.
The flexible type array that is returned will have two fields:
the _data field stores the _data part of the array.
the _mask field stores the _mask part of the array.
Parameters
None :
Returns
record : ndarray
A new flexible-type ndarray with two fields: the first element containing a value, the
second element containing the corresponding mask boolean. The returned record shape
matches self.shape.
Notes
A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value,
...) will be lost.
Examples
tostring(fill_value=None, order=C)
Return the array data as a string containing the raw bytes in the array.
The array is filled with a fill value before the string conversion.
Parameters
fill_value : scalar, optional
Value used to fill in the masked values. Deafult is None, in which case MaskedAr-
ray.fill_value is used.
order : {C,F,A}, optional
Notes
As for ndarray.tostring, information about the shape, dtype, etc., but also about fill_value, will be lost.
Examples
dump
Pickle an array
Notes
This is different from numpy.load, which does not use cPickle but loads the NumPy binary .npy format.
loads(strg)
Load a pickle from the current string.
The result of cPickle.loads(strg) is returned.
Parameters
strg : str
The string to load.
See Also:
dumps
Return a string corresponding to the pickling of a masked array.
ma.common_fill_value(a, b) Return the common filling value of two masked arrays, if any.
ma.default_fill_value(obj) Return the default fill value for the argument object.
ma.maximum_fill_value(obj) Return the minimum value that can be represented by the dtype of
an object.
ma.maximum_fill_value(obj) Return the minimum value that can be represented by the dtype of
an object.
ma.set_fill_value(a, fill_value) Set the filling value of a, if a is a masked array.
ma.MaskedArray.get_fill_value() Return the filling value of the masked array.
Set the filling value of the masked array.
ma.MaskedArray.set_fill_value([value])
ma.MaskedArray.fill_value Filling value.
common_fill_value(a, b)
Return the common filling value of two masked arrays, if any.
If a.fill_value == b.fill_value, return the fill value, otherwise return None.
Parameters
a, b : MaskedArray
The masked arrays for which to compare fill values.
Returns
fill_value : scalar or None
The common fill value, or None.
Examples
default_fill_value(obj)
Return the default fill value for the argument object.
The default filling value depends on the datatype of the input array or the type of the input scalar:
datatype default
bool True
int 999999
float 1.e20
complex 1.e20+0j
object ?
string N/A
Parameters
obj : ndarray, dtype or scalar
The array data-type or scalar for which the default fill value is returned.
Returns
fill_value : scalar
The default fill value.
Examples
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)
maximum_fill_value(obj)
Return the minimum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype.
Parameters
obj : {ndarray, dtype}
An object that can be queried for its numeric type.
Returns
val : scalar
The minimum representable value.
Raises
TypeError :
If obj isnt a suitable numeric type.
See Also:
minimum_fill_value
The inverse function.
set_fill_value
Set the filling value of a masked array.
MaskedArray.fill_value
Return current fill value.
Examples
maximum_fill_value(obj)
Return the minimum value that can be represented by the dtype of an object.
This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype.
Parameters
obj : {ndarray, dtype}
An object that can be queried for its numeric type.
Returns
val : scalar
The minimum representable value.
Raises
TypeError :
If obj isnt a suitable numeric type.
See Also:
minimum_fill_value
The inverse function.
set_fill_value
Set the filling value of a masked array.
MaskedArray.fill_value
Return current fill value.
Examples
set_fill_value(a, fill_value)
Set the filling value of a, if a is a masked array.
This function changes the fill value of the masked array a in place. If a is not a masked array, the function
returns silently, without doing anything.
Parameters
a : array_like
Input array.
fill_value : dtype
Filling value. A consistency test is performed to make sure the value is compatible with
the dtype of a.
Returns
None :
Nothing returned by this function.
See Also:
maximum_fill_value
Return the default fill value for a dtype.
MaskedArray.fill_value
Return current fill value.
MaskedArray.set_fill_value
Equivalent method.
Examples
>>> a = range(5)
>>> a
[0, 1, 2, 3, 4]
>>> ma.set_fill_value(a, 100)
>>> a
[0, 1, 2, 3, 4]
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> ma.set_fill_value(a, 100)
>>> a
array([0, 1, 2, 3, 4])
get_fill_value()
Return the filling value of the masked array.
Returns
fill_value : scalar
The filling value.
Examples
set_fill_value(value=None)
Set the filling value of the masked array.
Parameters
value : scalar, optional
The new filling value. Default is None, in which case a default based on the data type
is used.
See Also:
ma.set_fill_value
Equivalent function.
Examples
Reset to default:
>>> x.set_fill_value()
>>> x.fill_value
1e+20
fill_value
Filling value.
Arithmetics
ma.anom(self[, axis, dtype]) Compute the anomalies (deviations from the arithmetic mean) along
the given axis.
ma.anomalies(self[, axis, dtype]) Compute the anomalies (deviations from the arithmetic mean) along
the given axis.
ma.average(a[, axis, weights, Return the weighted average of array over the given axis.
returned])
ma.conjugate() Return the complex conjugate, element-wise.
ma.corrcoef(x[, y, rowvar, bias, Return correlation coefficients of the input array.
allow_masked])
ma.cov(x[, y, rowvar, bias, Estimate the covariance matrix.
allow_masked])
ma.cumsum(self[, axis, dtype, out]) Return the cumulative sum of the elements along the given axis.
ma.cumprod(self[, axis, dtype, out]) Return the cumulative product of the elements along the given axis.
ma.mean(self[, axis, dtype, out]) Returns the average of the array elements.
ma.median(a[, axis, out, Compute the median along the specified axis.
overwrite_input])
ma.power(a, b[, third]) Returns element-wise base array raised to power from second array.
ma.prod(self[, axis, dtype, out]) Return the product of the array elements over the given axis.
ma.std(self[, axis, dtype, out, ddof]) Compute the standard deviation along the specified axis.
ma.sum(self[, axis, dtype, out]) Return the sum of the array elements over the given axis.
ma.var(self[, axis, dtype, out, ddof]) Compute the variance along the specified axis.
ma.MaskedArray.anom([axis, dtype]) Compute the anomalies (deviations from the arithmetic mean) along
the given axis.
ma.MaskedArray.cumprod([axis, Return the cumulative product of the elements along the given axis.
dtype, out])
ma.MaskedArray.cumsum([axis, Return the cumulative sum of the elements along the given axis.
dtype, out])
ma.MaskedArray.mean([axis, dtype, Returns the average of the array elements.
out])
ma.MaskedArray.prod([axis, dtype, Return the product of the array elements over the given axis.
out])
ma.MaskedArray.std([axis, dtype, Compute the standard deviation along the specified axis.
out, ddof])
ma.MaskedArray.sum([axis, dtype, Return the sum of the array elements over the given axis.
out])
ma.MaskedArray.var([axis, dtype, Compute the variance along the specified axis.
out, ddof])
anom
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
anomalies
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
Examples
>>> x = np.ma.arange(6.).reshape(3, 2)
>>> print x
[[ 0. 1.]
[ 2. 3.]
[ 4. 5.]]
>>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
... returned=True)
>>> print avg
[2.66666666667 3.66666666667]
conjugate
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.
Parameters
x : array_like
Input value.
Returns
y : ndarray
Examples
>>> np.conjugate(1+2j)
(1-2j)
numpy.corrcoef
Equivalent function in top-level NumPy module.
cov
Estimate the covariance matrix.
Parameters
x : array_like
A 1-D or 2-D array containing multiple variables and observations. Each row of x
represents a variable, and each column a single observation of all those variables. Also
see rowvar below.
y : array_like, optional
An additional set of variables and observations. y has the same form as x.
rowvar : bool, optional
If rowvar is True (default), then each row represents a variable, with observations in the
columns. Otherwise, the relationship is transposed: each column represents a variable,
while the rows contain observations.
bias : bool, optional
Default normalization (False) is by (N-1), where N is the number of observations given
(unbiased estimate). If bias is True, then normalization is by N.
allow_masked : bool, optional
If True, masked values are propagated pair-wise: if a value is masked in x, the cor-
responding value is masked in y. If False, raises a ValueError exception when some
values are missing.
Raises
ValueError: :
Raised if some values are missing and allow_masked is False.
See Also:
numpy.cov
cumsum
Return the cumulative sum of the elements along the given axis. The cumulative sum is calculated over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array. axis may be negative, in which case it counts from the last to the
first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the elements are summed. If
dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a
precision less than that of the default platform integer. In that case, the default platform
integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumsum : ndarray.
A new array holding the result is returned unless out is specified, in which case a
reference to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
cumprod
Return the cumulative product of the elements along the given axis. The cumulative product is taken over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 1 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the product is computed. The default (axis = None) is to compute
over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements
are multiplied. If dtype has the value None and the type of a is an integer type
of precision less than the default platform integer, then the default platform integer
precision is used. Otherwise, the dtype is the same as that of a.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumprod : ndarray
A new array holding the result is returned unless out is specified, in which case a refer-
ence to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
mean
Returns the average of the array elements.
Masked entries are ignored. The average is taken over the flattened array by default, otherwise over the specified
axis. Refer to numpy.mean for the full documentation.
Parameters
a : array_like
Array containing numbers whose mean is desired. If a is not an array, a conversion is
attempted.
numpy.ma.mean
Equivalent function.
numpy.mean
Equivalent function on non-masked arrays.
numpy.ma.average
Weighted average.
Examples
If True, then allow use of memory of input array (a) for calculations. The input array
will be modified by the call to median. This will save memory when you do not need to
preserve the contents of the input array. Treat the input as undefined, but it will probably
be fully or partially sorted. Default is False. Note that, if overwrite_input is True, and
the input is not already an ndarray, an error will be raised.
Returns
median : ndarray
A new array holding the result is returned unless out is specified, in which case a refer-
ence to out is returned. Return data-type is float64 for integers and floats smaller than
float64, or the input data-type, otherwise.
See Also:
mean
Notes
Given a vector V with N non masked values, the median of V is the middle value of a sorted copy of V (Vs) - i.e.
Vs[(N-1)/2], when N is odd, or {Vs[N/2 - 1] + Vs[N/2]}/2 when N is even.
Examples
power(a, b, third=None)
Returns element-wise base array raised to power from second array.
This is the masked array version of numpy.power. For details see numpy.power.
See Also:
numpy.power
Notes
The out argument to numpy.power is not supported, third has to be None.
prod
Return the product of the array elements over the given axis. Masked elements are set to 1 internally for
computation.
Parameters
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the product is over all the
array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements are
multiplied. If dtype has the value None and the type of a is an integer type of precision
less than the default platform integer, then the default platform integer precision is used.
Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type will be cast if necessary.
Returns
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified axis removed. Returns
a 0d array when a is 1d or axis=None. Returns a reference to the specified output array
if specified.
See Also:
prod
equivalent function
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
std
Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard
deviation is computed for the flattened array by default, otherwise over the specified axis.
Parameters
a : array_like
Calculate the standard deviation of these values.
axis : int, optional
Axis along which the standard deviation is computed. The default is to compute the
standard deviation of the flattened array.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of integer type the default
is float64, for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type (of the calculated values) will be cast if necessary.
Notes
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =
sqrt(mean(abs(x - x.mean())**2)).
The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however,
ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate
of the variance for normally distributed variables. The standard deviation computed in this function is the
square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard
deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real
and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input
data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-
accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
sum
Return the sum of the array elements over the given axis. Masked elements are set to 0 internally.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator where the elements
are summed. If dtype has the value None and the type of a is an integer type of precision
less than the default platform integer, then the default platform integer precision is used.
Otherwise, the dtype is the same as that of a.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
sum_along_axis : MaskedArray or scalar
An array with the same shape as self, with the specified axis removed. If self is a 0-d
array, or if axis is None, a scalar is returned. If an output array is specified, a reference
to out is returned.
Examples
var
Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed
for the flattened array by default, otherwise over the specified axis.
Parameters
a : array_like
Array containing numbers whose variance is desired. If a is not an array, a conversion
is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type the default is float32;
for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type is cast if necessary.
ddof : int, optional
Delta Degrees of Freedom: the divisor used in calculation is N - ddof, where N
represents the number of elements. By default ddof is zero.
Returns
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise a reference to the
output array is returned.
See Also:
std
Standard deviation
mean
Average
numpy.doc.ufuncs
Section Output arguments
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x -
x.mean())**2).
The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the
divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of
the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for
normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and
nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the
input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a
higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
anom(axis=None, dtype=None)
Compute the anomalies (deviations from the arithmetic mean) along the given axis.
Returns an array of anomalies, with the same shape as the input and where the arithmetic mean is computed
along the given axis.
Parameters
axis : int, optional
Axis over which the anomalies are taken. The default is to use the mean of the flattened
array as reference.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as the array type.
See Also:
mean
Compute the mean of the array.
Examples
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1. 0. 1.],
mask = False,
fill_value = 1e+20)
of precision less than the default platform integer, then the default platform integer
precision is used. Otherwise, the dtype is the same as that of a.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumprod : ndarray
A new array holding the result is returned unless out is specified, in which case a refer-
ence to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis. The cumulative sum is calculated over the
flattened array by default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation. However, their position is saved, and the result
will be masked at the same locations.
Parameters
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (axis = None) is to compute over
the flattened array. axis may be negative, in which case it counts from the last to the
first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the elements are summed. If
dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a
precision less than that of the default platform integer. In that case, the default platform
integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape and
buffer length as the expected output but the type will be cast if necessary.
Returns
cumsum : ndarray.
A new array holding the result is returned unless out is specified, in which case a
reference to out is returned.
Notes
The mask is lost if out is not a valid MaskedArray !
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
numpy.ma.mean
Equivalent function.
numpy.mean
Equivalent function on non-masked arrays.
numpy.ma.average
Weighted average.
Examples
prod
equivalent function
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
Examples
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type (of the calculated values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof,
where N represents the number of elements. By default ddof is zero.
Returns
standard_deviation : ndarray, see dtype parameter above.
If out is None, return a new array containing the standard deviation, otherwise return a
reference to the output array.
See Also:
var, mean
numpy.doc.ufuncs
Section Output arguments
Notes
The standard deviation is the square root of the average of the squared deviations from the mean, i.e., std =
sqrt(mean(abs(x - x.mean())**2)).
The average squared deviation is normally calculated as x.sum() / N, where N = len(x). If, however,
ddof is specified, the divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an
unbiased estimator of the variance of the infinite population. ddof=0 provides a maximum likelihood estimate
of the variance for normally distributed variables. The standard deviation computed in this function is the
square root of the estimated variance, so even with ddof=1, it will not be an unbiased estimate of the standard
deviation per se.
Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real
and nonnegative.
For floating-point input, the std is computed using the same precision the input has. Depending on the input
data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a higher-
accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
Examples
Axis along which the variance is computed. The default is to compute the variance of
the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type the default is float32;
for arrays of float types it is the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have the same shape as the
expected output but the type is cast if necessary.
ddof : int, optional
Delta Degrees of Freedom: the divisor used in calculation is N - ddof, where N
represents the number of elements. By default ddof is zero.
Returns
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise a reference to the
output array is returned.
See Also:
std
Standard deviation
mean
Average
numpy.doc.ufuncs
Section Output arguments
Notes
The variance is the average of the squared deviations from the mean, i.e., var = mean(abs(x -
x.mean())**2).
The mean is normally calculated as x.sum() / N, where N = len(x). If, however, ddof is specified, the
divisor N - ddof is used instead. In standard statistical practice, ddof=1 provides an unbiased estimator of
the variance of the infinite population. ddof=0 provides a maximum likelihood estimate of the variance for
normally distributed variables.
Note that for complex numbers, the absolute value is taken before squaring, so that the result is always real and
nonnegative.
For floating-point input, the variance is computed using the same precision the input has. Depending on the
input data, this can cause the results to be inaccurate, especially for float32 (see example below). Specifying a
higher-accuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
Minimum/maximum
Returns
index_array : {integer_array}
Examples
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
maximum_fill_value
Returns the maximum filling value for a given datatype.
minimum_fill_value
Returns the minimum filling value for a given datatype.
Examples
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
If None, the index is into the flattened array, otherwise along the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of mini-
mum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved and it must be of the
right shape to hold the output.
Returns
{ndarray, scalar} :
If multi-dimension input, returns a new ndarray of indices to the minimum values along
the given axis. Otherwise, returns a scalar of index to the minimum values along the
given axis.
Examples
maximum_fill_value
Returns the maximum filling value for a given datatype.
Parameters
axis : {None, int}, optional
Axis along which to operate. By default, axis is None and the flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of the same shape and
buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values. If None, use the output of minimum_fill_value.
Returns
amin : array_like
New array holding the result. If out was specified, out is returned.
See Also:
minimum_fill_value
Returns the minimum filling value for a given datatype.
Sorting
ma.argsort(a[, axis, kind, order, fill_value]) Return an ndarray of indices that sort the array along the
specified axis.
ma.sort(a[, axis, kind, order, endwith, ...]) Sort the array, in-place
ma.MaskedArray.argsort([axis, kind, Return an ndarray of indices that sort the array along the
order, ...]) specified axis.
ma.MaskedArray.sort([axis, kind, order, Sort the array, in-place
...])
argsort(a, axis=None, kind=quicksort, order=None, fill_value=None)
Return an ndarray of indices that sort the array along the specified axis. Masked values are filled beforehand to
fill_value.
Parameters
axis : int, optional
Axis along which to sort. The default is -1 (last axis). If None, the flattened array is
used.
fill_value : var, optional
Value used to fill the array before sorting. The default is the fill_value attribute of the
input array.
kind : {quicksort, mergesort, heapsort}, optional
Sorting algorithm.
order : list, optional
When a is an array with fields defined, this argument specifies which fields to compare
first, second, etc. Not all fields need be specified.
Returns
index_array : ndarray, int
Array of indices that sort a along the specified axis. In other words,
a[index_array] yields a sorted a.
See Also:
sort
Describes sorting algorithms used.
lexsort
Indirect stable sort with multiple keys.
ndarray.sort
Inplace sort.
Notes
See sort for notes on the different sorting algorithms.
Examples
ndarray.sort
Method to sort an array in-place.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in a sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
sort
Describes sorting algorithms used.
lexsort
Indirect stable sort with multiple keys.
ndarray.sort
Inplace sort.
Notes
See sort for notes on the different sorting algorithms.
Examples
ndarray.sort
Method to sort an array in-place.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in a sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Algebra
numpy.diag
Equivalent function for ndarrays.
dot(a, b, strict=False)
Return the dot product of two arrays.
Note: Works only with 2-D arrays at the moment.
This function is the equivalent of numpy.dot that takes masked values into account, see numpy.dot for
details.
Parameters
a, b : ndarray
Inputs arrays.
strict : bool, optional
Whether masked data are propagated (True) or set to 0 (False) for the computation.
Default is False. Propagating the mask means that if a masked value appears in a row
or column, the whole row or column is considered masked.
See Also:
numpy.dot
Equivalent function for ndarrays.
Examples
identity
Return the identity array.
The identity array is a square array with ones on the main diagonal.
Parameters
n : int
Number of rows (and columns) in n x n output.
dtype : data-type, optional
Data-type of the output. Defaults to float.
Returns
out : ndarray
n x n array with its main diagonal set to one, and all other elements 0.
Examples
>>> np.identity(3)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
inner(a, b)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum
product over the last axes.
Parameters
a, b : array_like
If a and b are nonscalar, their last dimensions of must match.
Returns
out : ndarray
out.shape = a.shape[:-1] + b.shape[:-1]
Raises
ValueError :
If the last dimension of a and b has different size.
See Also:
tensordot
Sum products over arbitrary axes.
dot
Generalised matrix product, using second last dimension of b.
Notes
Masked values are replaced by 0.
Examples
Ordinary inner product for vectors:
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
A multidimensional example:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])
innerproduct(a, b)
Inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum
product over the last axes.
Parameters
a, b : array_like
If a and b are nonscalar, their last dimensions of must match.
Returns
out : ndarray
out.shape = a.shape[:-1] + b.shape[:-1]
Raises
ValueError :
If the last dimension of a and b has different size.
See Also:
tensordot
Sum products over arbitrary axes.
dot
Generalised matrix product, using second last dimension of b.
Notes
Masked values are replaced by 0.
Examples
Ordinary inner product for vectors:
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2
A multidimensional example:
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])
outer(a, b)
Compute the outer product of two vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [R57]
is:
Parameters
a, b : array_like, shape (M,), (N,)
First and second input vectors. Inputs are flattened if they are not already 1-dimensional.
Returns
out : ndarray, shape (M, N)
out[i, j] = a[i] * b[j]
Notes
Masked values are replaced by 0.
References
[R57]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:
outerproduct(a, b)
Compute the outer product of two vectors.
Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product [R58]
is:
Parameters
a, b : array_like, shape (M,), (N,)
First and second input vectors. Inputs are flattened if they are not already 1-dimensional.
Returns
out : ndarray, shape (M, N)
out[i, j] = a[i] * b[j]
Notes
Masked values are replaced by 0.
References
[R58]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:
trace
numpy.trace
equivalent function
transpose(a, axes=None)
Permute the dimensions of an array.
This function is exactly equivalent to numpy.transpose.
See Also:
numpy.transpose
Equivalent function in top-level NumPy module.
Examples
numpy.trace
equivalent function
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D array into a ma-
trix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes are given, their order in-
dicates how the axes are permuted (see Examples). If axes are not provided and a.shape = (i[0], i[1],
... i[n-2], i[n-1]), then a.transpose().shape = (i[n-1], i[n-2], ... i[1],
i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s j-th
axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
Polynomial fit
Notes
Masked values in the input array result in rows of zeros.
References
[R61]
Examples
The determinant of a square Vandermonde matrix is the product of the differences between the values of the
input vector:
>>> np.linalg.det(np.vander(x))
48.000000000000043
>>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
48
Switch determining nature of return value. When it is False (the default) just the coef-
ficients are returned, when True diagnostic information from the singular value decom-
position is also returned.
Returns
p : ndarray, shape (M,) or (M, K)
Polynomial coefficients, highest power first. If y was 2-D, the coefficients for k-th data
set are in p[:,k].
residuals, rank, singular_values, rcond : present only if full = True
Residuals of the least-squares fit, the effective rank of the scaled Vandermonde coeffi-
cient matrix, its singular values, and the specified value of rcond. For more details, see
linalg.lstsq.
See Also:
polyval
Computes polynomial values.
linalg.lstsq
Computes a least-squares fit.
scipy.interpolate.UnivariateSpline
Computes spline fits.
Notes
Any masked values in x is propagated in y, and vice-versa.
References
[R59], [R60]
Examples
>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179
>>> p(3.5)
-0.34732142857143039
>>> p(10)
22.579365079365115
-0.99999999999999445
>>> p30(4.5)
-0.10547061179440398
Illustration:
2.0
1.5
1.0
0.5
0.0
0.5
1.0
1.5
2.0
2 1 0 1 2 3 4 5 6
around
equivalent function
Parameters
a : array_like
Array containing elements to clip.
a_min : scalar or array_like
Minimum value.
a_max : scalar or array_like
Maximum value. If a_min or a_max are array_like, then they will be broadcasted to the
shape of a.
out : ndarray, optional
The results will be placed in this array. It may be the input array for in-place clipping.
out must be of the right shape to hold the output. Its type is preserved.
Returns
clipped_array : ndarray
An array with the elements of a, but where values < a_min are replaced with a_min, and
those > a_max with a_max.
See Also:
numpy.doc.ufuncs
Section Output arguments
Examples
>>> a = np.arange(10)
>>> np.clip(a, 1, 8)
array([1, 1, 2, 3, 4, 5, 6, 7, 8, 8])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, 3, 6, out=a)
array([3, 3, 3, 3, 4, 5, 6, 6, 6, 6])
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
Notes
If out is given and does not have a mask attribute, the mask of a is lost!
clip(a_min, a_max, out=None)
Return an array whose values are limited to [a_min, a_max].
Refer to numpy.clip for full documentation.
See Also:
numpy.clip
equivalent function
round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to numpy.around for full documentation.
See Also:
numpy.around
equivalent function
Miscellanea
ma.allequal(a, b[, fill_value]) Return True if all entries of a and b are equal, using
ma.allclose(a, b[, masked_equal, rtol, Returns True if two arrays are element-wise equal within a
...]) tolerance.
ma.apply_along_axis(func1d, axis, Apply a function to 1-D slices along the given axis.
arr, ...)
ma.arange([dtype]) Return evenly spaced values within a given interval.
ma.choose(indices, choices[, out, mode]) Use an index array to construct a new array from a set of choices.
ma.ediff1d(arr[, to_end, to_begin]) Compute the differences between consecutive elements of an array.
ma.indices(dimensions[, dtype]) Return an array representing the indices of a grid.
ma.where(condition[, x, y]) Return a masked array with elements from x or y, depending on
condition.
allequal(a, b, fill_value=True)
Return True if all entries of a and b are equal, using fill_value as a truth value where either or both are masked.
Parameters
a, b : array_like
Input arrays to compare.
fill_value : bool, optional
Whether masked values in a or b are considered equal (True) or not (False).
Returns
y : bool
Returns True if the two arrays are equal within the given tolerance, False otherwise. If
either array contains NaN, then False is returned.
See Also:
all, any, numpy.ma.allclose
Examples
Notes
If the following equation is element-wise True, then allclose returns True:
Return True if all elements of a and b are equal subject to given tolerances.
Examples
See Also:
apply_over_axes
Apply a function repeatedly over multiple axes.
Examples
For a function that doesnt return a scalar, the number of dimensions in outarr is the same as arr.
arange
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including
start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function,
but returns a ndarray rather than a list.
Parameters
start : number, optional
Start of interval. The interval includes this value. The default start value is 0.
stop : number
End of interval. The interval does not include this value.
step : number, optional
Spacing between values. For any output out, this is the distance between two adjacent
values, out[i+1] - out[i]. The default step size is 1. If step is specified, start
must also be given.
dtype : dtype
The type of the output array. If dtype is not given, infer the data type from the other
input arguments.
Returns
out : ndarray
Array of evenly spaced values.
linspace
Evenly spaced numbers with careful handling of endpoints.
ogrid
Arrays of evenly spaced numbers in N-dimensions
mgrid
Grid-shaped arrays of evenly spaced numbers in N-dimensions
Examples
>>> np.arange(3)
array([0, 1, 2])
>>> np.arange(3.0)
array([ 0., 1., 2.])
>>> np.arange(3,7)
array([3, 4, 5, 6])
>>> np.arange(3,7,2)
array([3, 5])
choose
equivalent function
Examples
numpy.ediff1d
Equivalent function for ndarrays.
Notes
The output shape is obtained by prepending the number of dimensions in front of the tuple of dimensions, i.e. if
dimensions is a tuple (r0, ..., rN-1) of length N, the output shape is (N,r0,...,rN-1).
The subarrays grid[k] contains the N-D array of indices along the k-th axis. Explicitly:
grid[k,i0,i1,...,iN-1] = ik
Examples
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
[4, 5, 6]])
Note that it would be more straightforward in the above example to extract the required elements directly with
x[:2, :3].
where(condition, x=None, y=None)
Return a masked array with elements from x or y, depending on condition.
Returns a masked array, shaped like condition, where the elements are from x when condition is True, and from
y otherwise. If neither x nor y are given, the function returns a tuple of indices where condition is True (the
result of condition.nonzero()).
Parameters
condition : array_like, bool
The condition to meet. For each True element, yield the corresponding element from x,
otherwise from y.
x, y : array_like, optional
Values from which to choose. x and y need to have the same shape as condition, or be
broadcast-able to that shape.
Returns
out : MaskedArray or tuple of ndarrays
The resulting masked array if x and y were given, otherwise the result of
condition.nonzero().
See Also:
numpy.where
Equivalent function in the top-level NumPy module.
Examples
Notes
Relevance is determined only roughly, by checking if the keywords occur in the function name, at the start of a
docstring, etc.
Examples
info([object, maxwidth, output, toplevel]) Get help information for a function, class, or module.
source(object[, output]) Print or write to a file the source code for a Numpy object.
info(object=None, maxwidth=76, output=<open file <stdout>, mode w at 0x2aaaaaac9198>,
toplevel=numpy)
Get help information for a function, class, or module.
Parameters
object : object or str, optional
Input object or name to get information about. If object is a numpy object, its docstring
is given. If it is a string, available modules are searched for matching objects. If None,
information about info itself is returned.
maxwidth : int, optional
Printing width.
output : file like object, optional
File like object that the output is written to, default is stdout. The object has to be
opened in w or a mode.
toplevel : str, optional
Start search at this level.
See Also:
source, lookfor
Notes
When used interactively with an object, np.info(obj) is equivalent to help(obj) on the Python prompt
or obj? on the IPython prompt.
Examples
>>> np.info(np.polyval)
polyval(p, x)
Evaluate the polynomial p at x.
...
>>> np.info(fft)
*** Found in numpy ***
Core FFT routines
...
*** Found in numpy.fft ***
fft(a, n=None, axis=-1)
...
*** Repeat reference found in numpy.fft.fftpack ***
*** Total of 3 references found. ***
Parameters
object : numpy object
Input object. This can be any object (function, class, module, ...).
output : file object, optional
If output not supplied then source code is printed to screen (sys.stdout). File object must
be created with either write w or append a modes.
See Also:
lookfor, info
Examples
>>> np.source(np.interp)
In file: /usr/lib/python2.6/dist-packages/numpy/lib/function_base.py
def interp(x, xp, fp, left=None, right=None):
""".... (full docstring printed)"""
if isinstance(x, (float, int, number)):
return compiled_interp([x], xp, fp, left, right).item()
else:
return compiled_interp(x, xp, fp, left, right)
>>> np.source(np.array)
Not available for this object.
getbuffer() Create a buffer object from the given object referencing a slice of length size starting at offset.
newbuffer(size) Return a new uninitialized buffer object of size bytes
getbuffer(obj, [offset, [size]])
Create a buffer object from the given object referencing a slice of length size starting at offset.
Default is the entire buffer. A read-write buffer is attempted followed by a read-only buffer.
Parameters
obj : object
offset : int, optional
size : int, optional
Returns
buffer_obj : buffer
Examples
\x00
>>> buf
<read-write buffer for 0x8af1e70, size 3, offset 1 at 0x8ba4ec0>
newbuffer(size)
Return a new uninitialized buffer object of size bytes
alterdot() Change dot, vdot, and innerproduct to use accelerated BLAS functions.
restoredot() Restore dot, vdot, and innerproduct to the default non-BLAS
setbufsize(size) Set the size of the buffer used in ufuncs.
getbufsize() Return the size of the buffer used in ufuncs.
alterdot()
Change dot, vdot, and innerproduct to use accelerated BLAS functions.
Typically, as a user of Numpy, you do not explicitly call this function. If Numpy is built with an accelerated
BLAS, this function is automatically called when Numpy is imported.
When Numpy is built with an accelerated BLAS like ATLAS, these functions are replaced to make use of the
faster implementations. The faster implementations only affect float32, float64, complex64, and complex128
arrays. Furthermore, the BLAS API only includes matrix-matrix, matrix-vector, and vector-vector products.
Products of arrays with larger dimensionalities use the built in functions and are not accelerated.
See Also:
restoredot
restoredot undoes the effects of alterdot.
restoredot()
Restore dot, vdot, and innerproduct to the default non-BLAS implementations.
Typically, the user will only need to call this when troubleshooting and installation problem, reproducing the
conditions of a build without an accelerated BLAS, or when being very careful about benchmarking linear
algebra operations.
See Also:
alterdot
restoredot undoes the effects of alterdot.
setbufsize(size)
Set the size of the buffer used in ufuncs.
Parameters
size : int
Size of buffer.
getbufsize()
Return the size of the buffer used in ufuncs.
This single module should provide all the common functionality for numpy tests in a single location, so that test scripts
can just import it and work right away.
3.24 Asserts
assert_array_almost_equal
compares array_like objects
assert_equal
tests objects for equality
Examples
>>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
np.array([1.0,2.33333334]), decimal=9)
...
<type exceptions.AssertionError>:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
x: array([ 1. , 2.33333333])
y: array([ 1. , 2.33333334])
assert_almost_equal
compares objects by decimals
assert_array_almost_equal
compares array_like objects by decimals
assert_equal
tests objects for equality
Examples
assert_almost_equal
simple version for comparing numbers
assert_array_equal
tests objects for equality
Examples
the first assert does not raise an exception
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
[1.0,2.333,np.nan])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
[1.0,2.33339,np.nan], decimal=5)
...
<type exceptions.AssertionError>:
AssertionError:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
x: array([ 1. , 2.33333, NaN])
y: array([ 1. , 2.33339, NaN])
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
[1.0,2.33333, 5], decimal=5)
<type exceptions.ValueError>:
ValueError:
Arrays are not almost equal
x: array([ 1. , 2.33333, NaN])
y: array([ 1. , 2.33333, 5. ])
assert_array_almost_equal
test objects for equality up to precision
assert_equal
tests objects for equality
Examples
the first assert does not raise an exception
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
[np.exp(0),2.33333, np.nan])
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
[1, np.sqrt(np.pi)**2, np.nan])
...
<type exceptions.ValueError>:
AssertionError:
Arrays are not equal
<BLANKLINE>
(mismatch 50.0%)
x: array([ 1. , 3.14159265, NaN])
y: array([ 1. , 3.14159265, NaN])
>>> np.testing.assert_array_almost_equal([1.0,np.pi,np.nan],
[1, np.sqrt(np.pi)**2, np.nan], decimal=15)
assert_array_equal
tests objects for equality
assert_array_almost_equal
test objects for equality up to precision
Examples
Raises
AssertionError :
If actual and desired are not equal.
Examples
Examples
3.24.1 Decorators
Notes
New in version 1.4.0.
knownfailureif(fail_condition, msg=None)
Make function raise KnownFailureTest exception if given condition is true.
If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that
may require costly imports, to delay the cost until the test suite is actually executed.
Parameters
fail_condition : bool or callable
Flag to determine whether to mark the decorated test as a known failure (if True) or not
(if False).
msg : str, optional
Message to give on raising a KnownFailureTest exception. Default is None.
Returns
decorator : function
Notes
The decorator itself is decorated with the nose.tools.make_decorator function in order to transmit
function name, and various other metadata.
setastest(tf=True)
Signals to nose that this function is or is not a test.
Parameters
tf : bool
If True, specifies that the decorated callable is a test. If False, specifies that the decorated
callable is not a test. Default is True.
Notes
This decorator cant use the nose namespace, because it can be called from a non-test module. See also istest
and nottest in nose.tools.
Examples
setastest can be used in the following way:
@setastest(False)
def func_with_test_in_name(arg1, arg2):
pass
skipif(skip_condition, msg=None)
Make function raise SkipTest exception if a given condition is true.
If the condition is a callable, it is used at runtime to dynamically make the decision. This is useful for tests that
may require costly imports, to delay the cost until the test suite is actually executed.
Parameters
skip_condition : bool or callable
Flag to determine whether to skip the decorated test.
msg : str, optional
Message to give on raising a SkipTest exception. Default is None.
Returns
decorator : function
Decorator which, when applied to a function, causes SkipTest to be raised when
skip_condition is True, and the function to be called normally otherwise.
Notes
The decorator itself is decorated with the nose.tools.make_decorator function in order to transmit
function name, and various other metadata.
slow(t)
Label a test as slow.
The exact definition of a slow test is obviously both subjective and hardware-dependent, but in general any
individual test that requires more than a second or two should be labeled as slow (the whole suite consits of
thousands of tests, so even a second is significant).
Parameters
t : callable
The test to label as slow.
Returns
t : callable
The decorated test t.
Examples
The numpy.testing module includes import decorators as dec. A test can be decorated as slow
like this:
@dec.slow
def test_big(self):
print Big, slow test
rundocs(filename=None, raise_on_error=True)
Run doctests found in the given file.
By default rundocs raises an AssertionError on failure.
Parameters
filename : str
The path to the file for which the doctests are run.
raise_on_error : bool
Whether to raise an AssertionError when a doctest fails. Default is True.
Notes
The doctests can be run by the user/developer by adding the doctests argument to the test() call. For
example, to run all tests (including doctests) for numpy.lib:
>>> np.lib.test(doctests=True)
Note: numpy.emath is a preferred alias for numpy.lib.scimath, available after numpy is imported.
Wrapper functions to more user-friendly calling of certain math functions whose output data-type is
different than the input data-type in certain domains of the input.
For example, for functions like log() with branch cuts, the versions in this module provide the mathematically valid
answers in the complex plane:
Similarly, sqrt(), other base logarithms, power() and trig functions are correctly handled. See their respective docstrings
for specific examples.
This module contains all functions in the numpy namespace, with the following replacement functions that return
matrices instead of ndarrays.
3.27.2 FFT
3.27.3 Other
as_array(*args, **kwds)
Dummy object that raises an ImportError if ctypes is not available.
Raises
ImportError :
If ctypes is not available.
as_ctypes(*args, **kwds)
Dummy object that raises an ImportError if ctypes is not available.
Raises
ImportError :
If ctypes is not available.
ctypes_load_library(*args, **kwds)
Dummy object that raises an ImportError if ctypes is not available.
Raises
ImportError :
If ctypes is not available.
load_library(*args, **kwds)
Dummy object that raises an ImportError if ctypes is not available.
Raises
ImportError :
If ctypes is not available.
ndpointer(dtype=None, ndim=None, shape=None, flags=None)
Array-checking restype/argtypes.
An ndpointer instance is used to describe an ndarray in restypes and argtypes specifications. This approach
is more flexible than using, for example, POINTER(c_double), since several restrictions can be specified,
which are verified upon calling the ctypes function. These include data type, number of dimensions, shape and
flags. If a given array does not satisfy the specified restrictions, a TypeError is raised.
Parameters
dtype : data-type, optional
Array data-type.
ndim : int, optional
Number of array dimensions.
shape : tuple of ints, optional
Array shape.
flags : str or tuple of str
Array flags; may be one or more of:
C_CONTIGUOUS / C / CONTIGUOUS
F_CONTIGUOUS / F / FORTRAN
OWNDATA / O
WRITEABLE / W
ALIGNED / A
UPDATEIFCOPY / U
Returns
klass : ndpointer type object
A type object, which is an _ndtpr instance containing dtype, ndim, shape and flags
information.
Raises
TypeError :
If a given array does not satisfy the specified restrictions.
Examples
This module provides a set of vectorized string operations for arrays of type numpy.string_ or
numpy.unicode_. All of them are based on the string methods in the Python standard library.
add(x1, x2) Return (x1 + x2), that is string concatenation, element-wise for a pair of array_likes of str
or unicode.
multiply(a, i) Return (a * i), that is string multiple concatenation, element-wise.
mod(a, values) Return (a % i), that is pre-Python 2.6 string formatting
capitalize(a) Return a copy of a with only the first character of each element capitalized.
center(a, width[, Return a copy of a with its elements centered in a string of length width.
fillchar])
decode(a[, Calls str.decode element-wise.
encoding, errors])
encode(a[, Calls str.encode element-wise.
encoding, errors])
join(sep, seq) Return a string which is the concatenation of the strings in the sequence seq.
ljust(a, width[, Return an array with the elements of a left-justified in a string of length width.
fillchar])
lower(a) Return an array with the elements of a converted to lowercase.
lstrip(a[, For each element in a, return a copy with the leading characters removed.
chars])
partition
replace(a, old, For each element in a, return a copy of the string with all occurrences of substring old
new[, count]) replaced by new.
rjust(a, width[, Return an array with the elements of a right-justified in a string of length width.
fillchar])
rpartition
rsplit(a[, sep, For each element in a, return a list of the words in the string, using sep as the delimiter
maxsplit]) string.
rstrip(a[, For each element in a, return a copy with the trailing characters removed.
chars])
split(a[, sep, For each element in a, return a list of the words in the string, using sep as the delimiter
maxsplit]) string.
splitlines(a[, For each element in a, return a list of the lines in the element, breaking at line boundaries.
keepends])
strip(a[, chars]) For each element in a, return a copy with the leading and trailing characters removed.
swapcase(a) For each element in a, return a copy of the string with uppercase characters converted to
lowercase and vice versa.
title(a) For each element in a, return a titlecased version of the string: words start with uppercase
characters, all remaining cased characters are lowercase.
translate(a, For each element in a, return a copy of the string where all characters occurring in the
table[, optional argument deletechars are removed, and the remaining characters have been
deletechars]) mapped through the given translation table.
upper(a) Return an array with the elements of a converted to uppercase.
zfill(a, width) Return the numeric string left-filled with zeros in a string of length width.
add(x1, x2)
Return (x1 + x2), that is string concatenation, element-wise for a pair of array_likes of str or unicode.
Parameters
x1 : array_like of str or unicode
x2 : array_like of str or unicode
Returns
out : ndarray
Output array of string_ or unicode_, depending on input types
multiply(a, i)
Return (a * i), that is string multiple concatenation, element-wise.
Values in i of less than 0 are treated as 0 (which yields an empty string).
Parameters
a : array_like of str or unicode
i : array_like of ints
Returns
out : ndarray
Output array of str or unicode, depending on input types
mod(a, values)
Return (a % i), that is pre-Python 2.6 string formatting (iterpolation), element-wise for a pair of array_likes of
str or unicode.
Parameters
a : array_like of str or unicode
values : array_like of values
These values will be element-wise interpolated into the string.
Returns
out : ndarray
Output array of str or unicode, depending on input types
See Also:
str.__mod__
capitalize(a)
Return a copy of a with only the first character of each element capitalized.
Calls str.capitalize element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array_like of str or unicode
Returns
out : ndarray
Output array of str or unicode, depending on input types
See Also:
str.capitalize
Examples
>>> c = np.array([a1b2,1b2a,b2a1,2a1b],S4); c
array([a1b2, 1b2a, b2a1, 2a1b],
dtype=|S4)
>>> np.char.capitalize(c)
array([A1b2, 1b2a, B2a1, 2a1b],
dtype=|S4)
Notes
The type of the result will depend on the encoding specified.
Examples
The set of available codecs comes from the Python standard library, and may be extended at runtime. For more
information, see the codecs module.
Parameters
a : array_like of str or unicode
encoding : str, optional
The name of an encoding
errors : str, optional
Specifies how to handle encoding errors
Returns
out : ndarray
See Also:
str.encode
Notes
The type of the result will depend on the encoding specified.
join(sep, seq)
Return a string which is the concatenation of the strings in the sequence seq.
Calls str.join element-wise.
Parameters
sep : array_like of str or unicode
seq : array_like of str or unicode
Returns
out : ndarray
Output array of str or unicode, depending on input types
See Also:
str.join
ljust(a, width, fillchar= )
Return an array with the elements of a left-justified in a string of length width.
Calls str.ljust element-wise.
Parameters
a : array_like of str or unicode
width : int
The length of the resulting strings
fillchar : str or unicode, optional
The character to use for padding
Returns
out : ndarray
Output array of str or unicode, depending on input type
See Also:
str.ljust
lower(a)
Return an array with the elements of a converted to lowercase.
Call str.lower element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array-like of str or unicode
Returns
out : ndarray, str or unicode
Output array of str or unicode, depending on input type
See Also:
str.lower
Examples
lstrip(a, chars=None)
For each element in a, return a copy with the leading characters removed.
Calls str.lstrip element-wise.
Parameters
a : array-like of str or unicode
chars : str or unicode, optional
The chars argument is a string specifying the set of characters to be removed. If omitted
or None, the chars argument defaults to removing whitespace. The chars argument is
not a prefix; rather, all combinations of its values are stripped.
Returns
out : ndarray, str or unicode
Output array of str or unicode, depending on input type
See Also:
str.lstrip
Examples
Examples
Returns
out : ndarray
Array of list objects
See Also:
str.split, rsplit
splitlines(a, keepends=None)
For each element in a, return a list of the lines in the element, breaking at line boundaries.
Calls str.splitlines element-wise.
Parameters
a : array_like of str or unicode
keepends : bool, optional
Line breaks are not included in the resulting list unless keepends is given and true.
Returns
out : ndarray
Array of list objects
See Also:
str.splitlines
strip(a, chars=None)
For each element in a, return a copy with the leading and trailing characters removed.
Calls str.rstrip element-wise.
Parameters
a : array-like of str or unicode
chars : str or unicode, optional
The chars argument is a string specifying the set of characters to be removed. If omitted
or None, the chars argument defaults to removing whitespace. The chars argument is
not a prefix or suffix; rather, all combinations of its values are stripped.
Returns
out : ndarray
Output array of str or unicode, depending on input type
See Also:
str.strip
Examples
swapcase(a)
For each element in a, return a copy of the string with uppercase characters converted to lowercase and vice
versa.
Calls str.swapcase element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array-like of str or unicode
Returns
out : ndarray
Output array of str or unicode, depending on input type
See Also:
str.swapcase
Examples
title(a)
For each element in a, return a titlecased version of the string: words start with uppercase characters, all
remaining cased characters are lowercase.
Calls str.title element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array-like of str or unicode
Returns
out : ndarray
Output array of str or unicode, depending on input type
See Also:
str.title
Examples
Examples
zfill(a, width)
Return the numeric string left-filled with zeros in a string of length width.
Calls str.zfill element-wise.
Parameters
a : array-like of str or unicode
width : int
Returns
out : ndarray
Output array of str or unicode, depending on input type
See Also:
str.zfill
3.31.2 Comparison
Unlike the standard numpy comparison operators, the ones in the char module strip trailing whitespace characters
before performing the comparison.
equal(x1, x2) Return (x1 == x2) element-wise.
not_equal(x1, x2) Return (x1 != x2) element-wise.
greater_equal(x1, x2) Return (x1 >= x2) element-wise.
less_equal(x1, x2) Return (x1 <= x2) element-wise.
greater(x1, x2) Return (x1 > x2) element-wise.
less(x1, x2) Return (x1 < x2) element-wise.
equal(x1, x2)
Return (x1 == x2) element-wise.
Unlike numpy.equal, this comparison is performed by first stripping whitespace characters from the end of
the string. This behavior is provided for backward-compatibility with numarray.
Parameters
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also:
not_equal, greater_equal, less_equal, greater, less
not_equal(x1, x2)
Return (x1 != x2) element-wise.
Unlike numpy.not_equal, this comparison is performed by first stripping whitespace characters from the
end of the string. This behavior is provided for backward-compatibility with numarray.
Parameters
x1, x2 : array_like of str or unicode
Input arrays of the same shape.
Returns
out : {ndarray, bool}
Output array of bools, or a single bool if x1 and x2 are scalars.
See Also:
equal, greater_equal, less_equal, greater, less
greater_equal(x1, x2)
Return (x1 >= x2) element-wise.
Unlike numpy.greater_equal, this comparison is performed by first stripping whitespace characters from
the end of the string. This behavior is provided for backward-compatibility with numarray.
Parameters
x1, x2 : array_like of str or unicode
See Also:
equal, not_equal, greater_equal, less_equal, greater
count(a, sub[, start, Returns an array with the number of non-overlapping occurrences of substring sub in
end]) the range [start, end].
len
find(a, sub[, start, For each element, return the lowest index in the string where substring sub is found.
end])
index(a, sub[, start, Like find, but raises ValueError when the substring is not found.
end])
isalpha(a) Returns true for each element if all characters in the string are alphabetic and there is at
least one character, false otherwise.
isdecimal(a) For each element in a, return True if there are only decimal
isdigit(a) Returns true for each element if all characters in the string are digits and there is at least
one character, false otherwise.
islower(a) Returns true for each element if all cased characters in the string are lowercase and
there is at least one cased character, false otherwise.
isnumeric(a) For each element in a, return True if there are only numeric
isspace(a) Returns true for each element if there are only whitespace characters in the string and
there is at least one character, false otherwise.
istitle(a) Returns true for each element if the element is a titlecased string and there is at least
one character, false otherwise.
isupper(a) Returns true for each element if all cased characters in the string are uppercase and
there is at least one character, false otherwise.
rfind(a, sub[, start, For each element in a, return the highest index in the string where substring sub is
end]) found, such that sub is contained within [start, end].
rindex(a, sub[, start, Like rfind, but raises ValueError when the substring sub is
end])
startswith(a, Returns a boolean array which is True where the string element
prefix[, start, end])
count(a, sub, start=0, end=None)
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start, end].
Calls str.count element-wise.
Parameters
a : array_like of str or unicode
sub : str or unicode
The substring to search for.
start, end : int, optional
Optional arguments start and end are interpreted as slice notation to specify the range
in which to count.
Returns
out : ndarray
Output array of ints.
See Also:
str.count
Examples
Returns
out : ndarray
Output array of bools
See Also:
str.islower
isnumeric(a)
For each element in a, return True if there are only numeric characters in the element.
Calls unicode.isnumeric element-wise.
Numeric characters include digit characters, and all characters that have the Unicode numeric value property,
e.g. U+2155, VULGAR FRACTION ONE FIFTH.
Parameters
a : array-like of unicode
Returns
out : ndarray
Array of booleans
See Also:
unicode.isnumeric
isspace(a)
Returns true for each element if there are only whitespace characters in the string and there is at least one
character, false otherwise.
Calls str.isspace element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array_like of str or unicode
Returns
out : ndarray
Output array of bools
See Also:
str.isspace
istitle(a)
Returns true for each element if the element is a titlecased string and there is at least one character, false
otherwise.
Call str.istitle element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array_like of str or unicode
Returns
out : ndarray
Output array of bools
See Also:
str.istitle
isupper(a)
Returns true for each element if all cased characters in the string are uppercase and there is at least one character,
false otherwise.
Call str.isupper element-wise.
For 8-bit strings, this method is locale-dependent.
Parameters
a : array_like of str or unicode
Returns
out : ndarray
Output array of bools
See Also:
str.isupper
rfind(a, sub, start=0, end=None)
For each element in a, return the highest index in the string where substring sub is found, such that sub is
contained within [start, end].
Calls str.rfind element-wise.
Parameters
a : array-like of str or unicode
sub : str or unicode
start, end : int, optional
Optional arguments start and end are interpreted as in slice notation.
Returns
out : ndarray
Output array of ints. Return -1 on failure.
See Also:
str.rfind
rindex(a, sub, start=0, end=None)
Like rfind, but raises ValueError when the substring sub is not found.
Calls str.rindex element-wise.
Parameters
a : array-like of str or unicode
sub : str or unicode
start, end : int, optional
Returns
out : ndarray
Output array of ints.
See Also:
rfind, str.rindex
Examples
Methods
astype(t)
Copy of the array, cast to a specified type.
Parameters
t : string or dtype
Typecode or data-type to which the array is cast.
Examples
>>> x.astype(int)
array([1, 2, 2])
copy(order=C)
Return a copy of the array.
Parameters
order : {C, F, A}, optional
By default, the result is stored in C-contiguous (row-major) order in memory. If order is
F, the result has Fortran (column-major) order. If order is A (Any), then the result
has the same order as the input.
Examples
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
[0, 0, 0]])
>>> y
array([[1, 2, 3],
[4, 5, 6]])
>>> y.flags[C_CONTIGUOUS]
True
dump(file)
Dump a pickle of the array to the specified file. The array can be read back with pickle.load or numpy.load.
Parameters
file : str
A string naming the dump file.
dumps()
Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an
array.
Parameters
None :
encode(encoding=None, errors=None)
Calls str.encode element-wise.
See Also:
char.encode
endswith(suffix, start=0, end=None)
Returns a boolean array which is True where the string element in self ends with suffix, otherwise False.
See Also:
char.endswith
expandtabs(tabsize=8)
Return a copy of each string element where all tab characters are replaced by one or more spaces.
See Also:
char.expandtabs
fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
Parameters
order : {C, F}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order. The default is C.
Returns
y : ndarray
A copy of the input array, flattened to one dimension.
See Also:
ravel
Return a flattened array.
flat
A 1-D flat iterator over the array.
Examples
getfield(dtype, offset)
Returns a field of the given array as a certain type.
A field is a view of the array data with each itemsize determined by the given type and the offset into the
current array, i.e. from offset * dtype.itemsize to (offset+1) * dtype.itemsize.
Parameters
dtype : str
String denoting the data type of the field.
offset : int
Number of dtype.itemsizes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
>>> x.dtype
dtype(complex128)
>>> x.getfield(complex128, 0) # == x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 1.+1.j]])
If the argument dtype is the same as x.dtype, then offset != 0 raises a ValueError:
>>> x.getfield(complex128, 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Need 0 <= offset <= 0 for requested type but received offset = 1
>>> x.getfield(float64, 0)
array([[ 1., 0.],
[ 0., 1.]])
>>> x.getfield(float64, 1)
array([[ 1.77658241e-307, 0.00000000e+000],
[ 0.00000000e+000, 1.77658241e-307]])
See Also:
char.islower
isnumeric()
For each element in self, return True if there are only numeric characters in the element.
See Also:
char.isnumeric
isspace()
Returns true for each element if there are only whitespace characters in the string and there is at least one
character, false otherwise.
See Also:
char.isspace
istitle()
Returns true for each element if the element is a titlecased string and there is at least one character, false
otherwise.
See Also:
char.istitle
isupper()
Returns true for each element if all cased characters in the string are uppercase and there is at least one
character, false otherwise.
See Also:
char.isupper
item(*args)
Copy an element of an array to a standard Python scalar and return it.
Parameters
*args : Arguments (variable number and type)
none: in this case, the method only works for arrays with one element (a.size == 1), which
element is copied into a standard Python scalar object and returned.
int_type: this argument is interpreted as a flat index into the array, specifying which ele-
ment to copy and return.
tuple of int_types: functions as does a single int_type argument, except that the argument
is interpreted as an nd-index into the array.
Returns
z : Standard Python scalar object
A copy of the specified element of the array as a suitable Python scalar
Notes
When the data type of a is longdouble or clongdouble, item() returns a scalar array object because there is
no available Python scalar that would not lose information. Void arrays return a buffer object for item(),
unless fields are defined, in which case a tuple is returned.
item is very similar to a[args], except, instead of an array scalar, a standard Python scalar is returned. This
can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array
using Pythons optimized math.
Examples
join(seq)
Return a string which is the concatenation of the strings in the sequence seq.
See Also:
char.join
ljust(width, fillchar= )
Return an array with the elements of self left-justified in a string of length width.
See Also:
char.ljust
lower()
Return an array with the elements of self converted to lowercase.
See Also:
char.lower
lstrip(chars=None)
For each element in self, return a copy with the leading characters removed.
See Also:
char.lstrip
nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
numpy.put
equivalent function
ravel([order])
Return a flattened array.
Refer to numpy.ravel for full documentation.
See Also:
numpy.ravel
equivalent function
ndarray.flat
a flat iterator on the array.
repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
numpy.reshape
equivalent function
resize(new_shape, refcheck=True)
Change shape and size of array in-place.
Parameters
new_shape : tuple of ints, or n ints
Shape of resized array.
refcheck : bool, optional
If False, reference count will not be checked. Default is True.
Returns
None :
Raises
ValueError :
If a does not own its own data or references or views to it exist, and the data memory
must be changed.
SystemError :
resize
Return a new array with the specified shape.
Notes
This reallocates space for the data area if necessary.
Only contiguous arrays (data elements consecutive in memory) can be resized.
The purpose of the reference count check is to make sure you do not use this array as a buffer for another
Python object and then reallocate the memory. However, reference counts can increase in other ways so if
you are sure that you have not shared the memory for this array with another Python object, then you may
safely set refcheck to False.
Examples
Shrinking an array: array is flattened (in the order that the data are stored in memory), resized, and re-
shaped:
Enlarging an array: as above, but missing entries are filled with zeros:
>>> c = a
>>> a.resize((1, 1))
...
ValueError: cannot resize an array that has been referenced ...
numpy.searchsorted
equivalent function
See Also:
getfield
Examples
>>> x = np.eye(3)
>>> x.getfield(np.float64)
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
>>> x.setfield(3, np.int32)
>>> x.getfield(np.int32)
array([[3, 3, 3],
[3, 3, 3],
[3, 3, 3]])
>>> x
array([[ 1.00000000e+000, 1.48219694e-323, 1.48219694e-323],
[ 1.48219694e-323, 1.00000000e+000, 1.48219694e-323],
[ 1.48219694e-323, 1.48219694e-323, 1.00000000e+000]])
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
Notes
Array flags provide information about how the memory area used for the array is to be interpreted. There
are 6 Boolean flags in use, only three of which can be changed by the user: UPDATEIFCOPY, WRITE-
ABLE, and ALIGNED.
WRITEABLE (W) the data area can be written to;
ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the com-
piler);
UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .base). When this array is
deallocated, the base array will be updated with the contents of this array.
All flags can be accessed using their first (upper case) letter as well as the full name.
Examples
>>> y
array([[3, 1, 7],
[2, 0, 0],
[8, 5, 9]])
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
>>> y.setflags(write=0, align=0)
>>> y.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : False
UPDATEIFCOPY : False
>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True
numpy.sort
Return a sorted copy of an array.
argsort
Indirect sort.
lexsort
Indirect stable sort on multiple keys.
searchsorted
Find elements in sorted array.
Notes
See sort for notes on the different sorting algorithms.
Examples
Use the order keyword to specify a field to use when sorting a structured array:
split(sep=None, maxsplit=None)
For each element in self, return a list of the words in the string, using sep as the delimiter string.
See Also:
char.split
splitlines(keepends=None)
For each element in self, return a list of the lines in the element, breaking at line boundaries.
See Also:
char.splitlines
squeeze()
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
See Also:
numpy.swapaxes
equivalent function
swapcase()
For each element in self, return a copy of the string with uppercase characters converted to lowercase and
vice versa.
See Also:
char.swapcase
take(indices, axis=None, out=None, mode=raise)
Return an array formed from the elements of a at the given indices.
Refer to numpy.take for full documentation.
See Also:
numpy.take
equivalent function
title()
For each element in self, return a titlecased version of the string: words start with uppercase characters, all
remaining cased characters are lowercase.
See Also:
char.title
tofile(fid, sep="", format="%s")
Write array to a file as text or binary (default).
Data is always written in C order, independent of the order of a. The data produced by this method can
be recovered using the function fromfile().
Parameters
fid : file or str
An open file object, or a string containing a filename.
sep : str
Separator between array items for text output. If (empty), a binary file is written,
equivalent to file.write(a.tostring()).
format : str
Format string for text file output. Each entry in the array is formatted to text by first
converting it to the closest Python type, and then using format % item.
Notes
This is a convenience function for quick storage of array data. Information on endianness and precision
is lost, so this method is not a good choice for files intended to archive data or transport data between
machines with different endianness. Some of these problems can be overcome by outputting the data as
text files, at the expense of speed and file size.
tolist()
Return the array as a (possibly nested) list.
Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible
Python type.
Parameters
none :
Returns
y : list
The possibly nested list of array elements.
Notes
The array may be recreated, a = np.array(a.tolist()).
Examples
tostring(order=C)
Construct a Python string containing the raw data bytes in the array.
Constructs a Python string showing a copy of the raw contents of data memory. The string can be produced
in either C or Fortran, or Any order (the default is C-order). Any order means C-order unless the
F_CONTIGUOUS flag in the array is set, in which case it means Fortran order.
Parameters
order : {C, F, None}, optional
Order of the data for multidimensional arrays: C, Fortran, or the same as for the original
array.
Returns
s : str
A Python string exhibiting a copy of as raw data.
Examples
translate(table, deletechars=None)
For each element in self, return a copy of the string where all characters occurring in the optional argument
deletechars are removed, and the remaining characters have been mapped through the given translation
table.
See Also:
char.translate
transpose(*axes)
Returns a view of the array with axes transposed.
For a 1-D array, this has no effect. (To change between column and row vectors, first cast the 1-D ar-
ray into a matrix object.) For a 2-D array, this is the usual matrix transpose. For an n-D array, if axes
are given, their order indicates how the axes are permuted (see Examples). If axes are not provided
and a.shape = (i[0], i[1], ... i[n-2], i[n-1]), then a.transpose().shape
= (i[n-1], i[n-2], ... i[1], i[0]).
Parameters
axes : None, tuple of ints, or n ints
None or no argument: reverses the order of the axes.
tuple of ints: i in the j-th place in the tuple means as i-th axis becomes a.transpose()s
j-th axis.
n ints: same as an n-tuple of the same ints (this form is intended simply as a convenience
alternative to the tuple form)
Returns
out : ndarray
View of a, with axes suitably permuted.
See Also:
ndarray.T
Array property returning the array transposed.
Examples
upper()
Return an array with the elements of self converted to uppercase.
See Also:
char.upper
view(dtype=None, type=None)
New view of array with the same data.
Parameters
dtype : data-type
Data-type descriptor of the returned view, e.g. float32 or int16.
Notes
a.view() is used two different ways.
a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the arrays memory with a different
dtype. This can cause a reinterpretation of the bytes of memory.
a.view(ndarray_subclass), or a.view(type=ndarray_subclass), just returns an instance of ndarray_subclass
that looks at the same array (same shape, dtype, etc.). This does not cause a reinterpretation of the memory.
Examples
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)
zfill(width)
Return the numeric string left-filled with zeros in a string of length width.
See Also:
char.zfill
FOUR
PACKAGING (NUMPY.DISTUTILS)
NumPy provides enhanced distutils functionality to make it easier to build and install sub-packages, auto-generate
code, and extension modules that use Fortran-compiled libraries. To use features of NumPy distutils, use the
setup command from numpy.distutils.core. A useful Configuration class is also provided in
numpy.distutils.misc_util that can make it easier to construct keyword arguments to pass to the setup
function (by passing the dictionary obtained from the todict() method of the class). More information is available in
the NumPy Distutils Users Guide in <site-packages>/numpy/doc/DISTUTILS.txt.
4.1.1 misc_util
Configuration(**attrs[,
package_name, ...])
get_numpy_include_dirs()
dict_append(d, **kws)
appendpath(prefix, path)
allpath(name) Convert a /-separated pathname to one using the OSs path separator.
dot_join(*args)
generate_config_py(target) Generate config.py file containing system_info information used during
building the package.
get_cmd(cmdname[, _cache])
terminal_has_colors()
red_text(s)
green_text(s)
yellow_text(s)
blue_text(s)
cyan_text(s)
cyg2win32(path)
all_strings(lst) Return True if all items in lst are string objects.
has_f_sources(sources) Return True if sources contains Fortran files
has_cxx_sources(sources) Return True if sources contains C++ files
filter_sources(sources) Return four lists of filenames containing
get_dependencies(sources)
is_local_src_dir(directory) Return true if directory is local directory.
get_ext_source_files(ext)
get_script_files(scripts)
999
NumPy Reference, Release 2.0.0.dev8464
get_numpy_include_dirs()
dict_append(d, **kws)
appendpath(prefix, path)
allpath(name)
Convert a /-separated pathname to one using the OSs path separator.
dot_join(*args)
generate_config_py(target)
Generate config.py file containing system_info information used during building the package.
Usage:
config[py_modules].append((packagename, __config__,generate_config_py))
get_cmd(cmdname, _cache={})
terminal_has_colors()
red_text(s)
green_text(s)
yellow_text(s)
blue_text(s)
cyan_text(s)
cyg2win32(path)
all_strings(lst)
Return True if all items in lst are string objects.
has_f_sources(sources)
Return True if sources contains Fortran files
has_cxx_sources(sources)
Return True if sources contains C++ files
filter_sources(sources)
Return four lists of filenames containing C, C++, Fortran, and Fortran 90 module sources, respectively.
get_dependencies(sources)
is_local_src_dir(directory)
Return true if directory is local directory.
get_ext_source_files(ext)
get_script_files(scripts)
Examples
>>> setup(**config.todict())
get_distribution()
Return the distutils distribution object for self.
get_subpackage(subpackage_name, subpackage_path=None, parent_name=None, caller_level=1)
Return list of subpackage configurations.
Parameters
subpackage_name: str,None :
Name of the subpackage to get the configuration. * in subpackage_name is handled
as a wildcard.
subpackage_path: str :
If None, then the path is assumed to be the local path plus the subpackage_name. If a
setup.py file is not found in the subpackage_path, then a default configuration is used.
parent_name: str :
Parent name.
add_subpackage(subpackage_name, subpackage_path=None, standalone=False)
Add a sub-package to the current Configuration instance.
This is useful in a setup.py script for adding sub-packages to a package.
Parameters
subpackage_name: str :
name of the subpackage
subpackage_path: str :
if given, the subpackage path such as the subpackage is in subpackage_path / subpack-
age_name. If None,the subpackage is assumed to be located in the local path / subpack-
age_name.
standalone: bool :
add_data_files(*files)
Add data files to configuration data_files.
Parameters
files: sequence :
Argument(s) can be either
2-sequence (<datadir prefix>,<path to data file(s)>)
paths to data files where python datadir prefix defaults to package dir.
Notes
The form of each element of the files sequence is very flexible allowing many combinations of where to
get the files from the package and where they should ultimately be installed on the system. The most basic
usage is for an element of the files argument sequence to be a simple filename. This will cause that file
from the local path to be installed to the installation path of the self.name package (package path). The file
argument can also be a relative path in which case the entire relative path will be installed into the package
directory. Finally, the file can be an absolute path name in which case the file will be found at the absolute
path name but installed to the package path.
This basic behavior can be augmented by passing a 2-tuple in as the file argument. The first element of the
tuple should specify the relative path (under the package install directory) where the remaining sequence
of files should be installed to (it has nothing to do with the file-names in the source distribution). The
second element of the tuple is the sequence of files that should be installed. The files in this sequence can
be filenames, relative paths, or absolute paths. For absolute paths the file will be installed in the top-level
package installation directory (regardless of the first argument). Filenames and relative path names will be
installed in the package install directory under the path name given as the first element of the tuple.
Rules for installation paths:
1.file.txt -> (., file.txt)-> parent/file.txt
2.foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
3./foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
4.*.txt -> parent/a.txt, parent/b.txt
5.foo/*.txt -> parent/foo/a.txt, parent/foo/b.txt
6./.txt -> (, */.txt) -> parent/c/a.txt, parent/d/b.txt
7.(sun, file.txt) -> parent/sun/file.txt
8.(sun, bar/file.txt) -> parent/sun/file.txt
9.(sun, /foo/bar/file.txt) -> parent/sun/file.txt
10.(sun, *.txt) -> parent/sun/a.txt, parent/sun/b.txt
11.(sun, bar/*.txt) -> parent/sun/a.txt, parent/sun/b.txt
12.(sun/, */.txt) -> parent/sun/c/a.txt, parent/d/b.txt
An additional feature is that the path to a data-file can actually be a function that takes no arguments and
returns the actual path(s) to the data-files. This is useful when the data files are generated while building
the package.
Examples
Add files to the list of data_files to be included with the package.
>>> self.add_data_files(foo.dat,
... (fun, [gun.dat, nun/pun.dat, /tmp/sun.dat]),
... bar/cat.dat,
... /full/path/to/can.dat)
where <package install directory> is the package (or sub-package) directory such as
/usr/lib/python2.4/site-packages/mypackage (C: Python2.4 Lib site-packages mypackage) or
/usr/lib/python2.4/site- packages/mypackage/mysubpackage (C: Python2.4 Lib site-packages my-
package mysubpackage).
add_data_dir(data_path)
Recursively add files under data_path to data_files list.
Recursively add files under data_path to the list of data_files to be installed (and distributed). The data_path
can be either a relative path-name, or an absolute path-name, or a 2-tuple where the first argument shows
where in the install directory the data directory should be installed to.
Parameters
data_path: seq,str :
Argument can be either
2-sequence (<datadir suffix>,<path to data directory>)
path to data directory where python datadir suffix defaults to package dir.
Notes
Rules for installation paths:
foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar (gun, foo/bar) -> parent/gun foo/* -> (foo/a, foo/a),
(foo/b, foo/b) -> parent/foo/a, parent/foo/b (gun, foo/) -> (gun, foo/a), (gun, foo/b) -> gun (gun/, foo/)
-> parent/gun/a, parent/gun/b /foo/bar -> (bar, /foo/bar) -> parent/bar (gun, /foo/bar) -> parent/gun
(fun/ /gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar
Examples
For example suppose the source directory contains fun/foo.dat and fun/bar/car.dat:
>>> self.add_data_dir(fun)
>>> self.add_data_dir((sun, fun))
>>> self.add_data_dir((gun, /full/path/to/fun))
car.dat
sun/
foo.dat
bar/
car.dat
gun/
foo.dat
car.dat
add_include_dirs(*paths)
Add paths to configuration include directories.
Add the given sequence of paths to the beginning of the include_dirs list. This list will be visible to all
extension modules of the current package.
add_headers(*files)
Add installable headers to configuration.
Add the given sequence of files to the beginning of the headers list. By default, headers will be installed
under <python- include>/<self.name.replace(.,/)>/ directory. If an item of files is a tuple, then its first
argument specifies the actual installation location relative to the <python-include> path.
Parameters
files: str, seq :
Argument(s) can be either:
2-sequence (<includedir suffix>,<path to header file(s)>)
path(s) to header file(s) where python includedir suffix will default to package name.
add_extension(name, sources, **kw)
Add extension to configuration.
Create and add an Extension instance to the ext_modules list. This method also takes the following optional
keyword arguments that are passed on to the Extension constructor.
Parameters
name: str :
name of the extension
sources: seq :
list of the sources. The list of sources may contain functions (called source generators)
which must take an extension instance and a build directory as inputs and return a source
file or list of source files or None. If None is returned then no sources are generated.
If the Extension instance has no sources after processing all source generators, then no
extension module is built.
include_dirs: :
define_macros: :
undef_macros: :
library_dirs: :
libraries: :
runtime_library_dirs: :
extra_objects: :
extra_compile_args: :
extra_link_args: :
export_symbols: :
swig_opts: :
depends: :
The depends list contains paths to files or directories that the sources of the extension
module depend on. If any path in the depends list is newer than the extension module,
then the module will be rebuilt.
language: :
f2py_options: :
module_dirs: :
extra_info: dict,list :
dict or list of dict of keywords to be appended to keywords.
Notes
The self.paths(...) method is applied to all lists that may contain paths.
add_library(name, sources, **build_info)
Add library to configuration.
Parameters
name : str
Name of the extension.
sources : sequence
List of the sources. The list of sources may contain functions (called source generators)
which must take an extension instance and a build directory as inputs and return a source
file or list of source files or None. If None is returned then no sources are generated.
If the Extension instance has no sources after processing all source generators, then no
extension module is built.
build_info : dict, optional
The following keys are allowed:
depends
macros
include_dirs
extra_compiler_args
f2py_options
language
add_scripts(*files)
Add scripts to configuration.
Add the sequence of files to the beginning of the scripts list. Scripts will be installed under the <prefix>/bin/
directory.
add_installed_library(name, sources, install_dir, build_info=None)
Similar to add_library, but the specified library is installed.
Most C libraries used with distutils are only used to build python extensions, but libraries built
through this method will be installed so that they can be reused by third-party packages.
Parameters
name : str
Name of the installed library.
sources : sequence
List of the librarys source files. See add_library for details.
install_dir : str
Path to install the library, relative to the current sub-package.
build_info : dict, optional
The following keys are allowed:
depends
macros
include_dirs
extra_compiler_args
f2py_options
language
Returns
None :
See Also:
add_library, add_npy_pkg_config, get_info
Notes
The best way to encode the options required to link against the specified C libraries is to use a libname.ini
file, and use get_info to retrieve the required options (see add_npy_pkg_config for more information).
add_npy_pkg_config(template, install_dir, subst_dict=None)
Generate and install a npy-pkg config file from a template.
The config file generated from template is installed in the given install directory, using subst_dict for
variable substitution.
Parameters
template : str
The path of the template, relatively to the current package path.
install_dir : str
Where to install the npy-pkg config file, relatively to the current package path.
subst_dict : dict, optional
If given, any string of the form @key@ will be replaced by subst_dict[key] in the
template file when installed. The install prefix is always available through the variable
@prefix@, since the install prefix is not easy to get reliably from setup.py.
See Also:
add_installed_library, get_info
Notes
This works for both standard installs and in-place builds, i.e. the @prefix@ refer to the source directory
for in-place builds.
Examples
[meta]
Name=@foo@
Version=1.0
Description=dummy description
[default]
Cflags=-I@prefix@/include
Libs=
[meta]
Name=bar
Version=1.0
Description=dummy description
[default]
Cflags=-Iprefix_dir/include
Libs=
Notes
True if a Fortran 77 compiler is available (because a simple Fortran 77 code was able to be compiled
successfully).
have_f90c()
Check for availability of Fortran 90 compiler.
Use it inside source generating function to ensure that setup distribution instance has been initialized.
Notes
True if a Fortran 90 compiler is available (because a simple Fortran 90 code was able to be compiled
successfully)
get_version(version_file=None, version_variable=None)
Try to get version string of a package.
Return a version string of the current package or None if the version information could not be detected.
Notes
This method scans files named __version__.py, <packagename>_version.py, version.py, and
__svn_version__.py for string variables version, __version__, and <packagename>_version, until a ver-
sion number is found.
make_svn_version_py(delete=True)
Appends a data function to the data_files list that will generate __svn_version__.py file to the current
package directory.
Generate package __svn_version__.py file from SVN revision number, it will be removed after python
exits but will be available when sdist, etc commands are executed.
Notes
If __svn_version__.py existed before, nothing is done.
This is intended for working with source directories that are in an SVN repository.
make_config_py(name=__config__)
Generate package __config__.py file containing system_info information used during building the pack-
age.
This file is installed to the package installation directory.
get_info(*names)
Get resources information.
Return information (from system_info.get_info) for all of the names in the argument list in a single dictio-
nary.
notfound_action:
0 - do nothing 1 - display warning message 2 - raise error
get_standard_file(fname)
Returns a list of files named fname from 1) System-wide directory (directory-location of this module) 2)
Users HOME directory (os.environ[HOME]) 3) Local directory
cpu
set_verbosity(v, force=False)
exec_command
Implements exec_command function that is (almost) equivalent to commands.getstatusoutput function but on NT,
DOS systems the returned status is actually correct (though, the returned status values may be different by a factor).
In addition, exec_command takes keyword arguments for (re-)defining environment variables.
Provides functions:
Functions
exec_command(command, **env[, execute_in, ...]) Return (status,output) of executed command.
find_executable(exe[, path, _cache]) Return full path of a executable or None.
get_exception()
get_pythonexe()
is_sequence(seq)
make_temp_file([suffix, prefix, text])
open_latin1(filename[, mode])
quote_arg(arg)
splitcmdline(line)
temp_file_name()
test(**kws)
test_cl(**kws)
test_execute_in(**kws)
test_nt(**kws)
test_posix(**kws)
test_svn(**kws)
Conventional C libraries (installed through add_library) are not installed, and are just used during the build (they
are statically linked). An installable C library is a pure C library, which does not depend on the python C runtime,
and is installed such that it may be used by third-party packages. To build and install the C library, you just use
the method add_installed_library instead of add_library, which takes the same arguments except for an additional
install_dir argument:
To make the necessary build options available to third parties, you could use the npy-pkg-config mechanism imple-
mented in numpy.distutils. This mechanism is based on a .ini file which contains all the options. A .ini file is
very similar to .pc files as used by the pkg-config unix utility:
[meta]
Name: foo
Version: 1.0
Description: foo library
[variables]
prefix = /home/user/local
libdir = ${prefix}/lib
includedir = ${prefix}/include
[default]
cflags = -I${includedir}
libs = -L${libdir} -lfoo
Generally, the file needs to be generated during the build, since it needs some information known at build time only
(e.g. prefix). This is mostly automatic if one uses the Configuration method add_npy_pkg_config. Assuming we have
a template file foo.ini.in as follows:
[meta]
Name: foo
Version: @version@
Description: foo library
[variables]
prefix = @prefix@
libdir = ${prefix}/lib
includedir = ${prefix}/include
[default]
cflags = -I${includedir}
libs = -L${libdir} -lfoo
This will install the file foo.ini into the directory package_dir/lib, and the foo.ini file will be generated from foo.ini.in,
where each @version@ will be replaced by subst_dict[version]. The dictionary has an additional prefix
substitution rule automatically added, which contains the install prefix (since this is not easy to get from setup.py).
npy-pkg-config files can also be installed at the same location as used for numpy, using the path returned from
get_npy_pkg_dir function.
An additional list of paths to look for .ini files can be given to get_info.
NumPy distutils supports automatic conversion of source files named <somefile>.src. This facility can be used to
maintain very similar code blocks requiring only simple changes between blocks. During the build phase of setup, if
a template file named <somefile>.src is encountered, a new file named <somefile> is constructed from the template
and placed in the build directory to be used instead. Two forms of template conversion are supported. The first form
occurs for files named named <file>.ext.src where ext is a recognized Fortran extension (f, f90, f95, f77, for, ftn, pyf).
The second form is used for all other cases.
This template converter will replicate all function and subroutine blocks in the file with names that contain <...>
according to the rules in <...>. The number of comma-separated words in <...> determines the number of times
the block is repeated. What these words are indicates what that repeat rule, <...>, should be replaced with in each
block. All of the repeat rules in a block must contain the same number of comma-separated words indicating the
number of times that block should be repeated. If the word in the repeat rule needs a comma, leftarrow, or rightarrow,
then prepend it with a backslash . If a word in the repeat rule matches \<index> then it will be replaced with the
<index>-th word in the same repeat specification. There are two forms for the repeat rule: named and short.
A named repeat rule is useful when the same set of repeats must be used several times in a block. It is specified using
<rule1=item1, item2, item3,..., itemN>, where N is the number of times the block should be repeated. On each repeat
of the block, the entire expression, <...> will be replaced first with item1, and then with item2, and so forth until N
repeats are accomplished. Once a named repeat specification has been introduced, the same repeat rule may be used
in the current block by referring only to the name (i.e. <rule1>.
A short repeat rule looks like <item1, item2, item3, ..., itemN>. The rule specifies that the entire expression, <...>
should be replaced first with item1, and then with item2, and so forth until N repeats are accomplished.
Pre-defined names
Non-Fortran files use a separate syntax for defining template blocks that should be repeated using a variable expansion
similar to the named repeat rules of the Fortran-specific repeats. The template rules for these files are:
1. /**begin repeat on a line by itself marks the beginning of a segment that should be repeated.
2. Named variable expansions are defined using #name=item1, item2, item3, ..., itemN# and placed on successive
lines. These variables are replaced in each repeat block with corresponding word. All named variables in the
same repeat block must define the same number of words.
3. In specifying the repeat rule for a named variable, item*N is short- hand for item, item, ..., item repeated N
times. In addition, parenthesis in combination with *N can be used for grouping several items that should be
repeated. Thus, #name=(item1, item2)*4# is equivalent to #name=item1, item2, item1, item2, item1, item2,
item1, item2#
4. */ on a line by itself marks the end of the the variable expansion naming. The next line is the first line that
will be repeated using the named rules.
5. Inside the block to be repeated, the variables that should be expanded are specified as @name@.
6. /**end repeat**/ on a line by itself marks the previous line as the last line of the block to be repeated.
FIVE
NUMPY C-API
Several new types are defined in the C-code. Most of these are accessible from Python, but a few are not exposed due
to their limited use. Every new Python type has an associated PyObject * with an internal structure that includes
a pointer to a method table that defines how the new object behaves in Python. When you receive a Python object
into C code, you always get a pointer to a PyObject structure. Because a PyObject structure is very generic and
defines only PyObject_HEAD, by itself it is not very interesting. However, different objects contain more details
after the PyObject_HEAD (but you have to cast to the correct type to access them or use accessor functions or
macros).
Python types are the functional equivalent in C of classes in Python. By constructing a new Python type you make
available a new object for Python. The ndarray object is an example of a new type defined in C. New types are defined
in C by two basic steps:
1. creating a C-structure (usually named Py{Name}Object) that is binary- compatible with the PyObject
structure itself but holds the additional information needed for that particular object;
2. populating the PyTypeObject table (pointed to by the ob_type member of the PyObject structure) with
pointers to functions that implement the desired behavior for the type.
1013
NumPy Reference, Release 2.0.0.dev8464
Instead of special method names which define behavior for Python classes, there are function tables which point to
functions that implement the desired results. Since Python 2.2, the PyTypeObject itself has become dynamic which
allows C types that can be sub-typed from other C-types in C, and sub-classed in Python. The children types inherit
the attributes and methods from their parent(s).
There are two major new types: the ndarray ( PyArray_Type ) and the ufunc ( PyUFunc_Type ). Ad-
ditional types play a supportive role: the PyArrayIter_Type, the PyArrayMultiIter_Type, and the
PyArrayDescr_Type . The PyArrayIter_Type is the type for a flat iterator for an ndarray (the object that
is returned when getting the flat attribute). The PyArrayMultiIter_Type is the type of the object returned
when calling broadcast (). It handles iteration and broadcasting over a collection of nested sequences. Also, the
PyArrayDescr_Type is the data-type-descriptor type whose instances describe the data. Finally, there are 21 new
scalar-array types which are new Python scalars corresponding to each of the fundamental data types available for
arrays. An additional 10 other types are place holders that allow the array scalars to fit into a hierarchy of actual
Python types.
PyArray_Type
PyArray_Type
The Python type of the ndarray is PyArray_Type. In C, every ndarray is a pointer to a PyArrayObject
structure. The ob_type member of this structure contains a pointer to the PyArray_Type typeobject.
PyArrayObject
The PyArrayObject C-structure contains all of the required information for an array. All instances of an
ndarray (and its subclasses) will have this structure. For future compatibility, these structure members should
normally be accessed using the provided macros. If you need a shorter name, then you can make use of
NPY_AO which is defined to be equivalent to PyArrayObject.
PyObject_HEAD
This is needed by all Python objects. It consists of (at least) a reference count member ( ob_refcnt ) and
a pointer to the typeobject ( ob_type ). (Other elements may also be present if Python was compiled with
special options see Include/object.h in the Python source tree for more information). The ob_type member
points to a Python type object.
char data
A pointer to the first element of the array. This pointer can (and normally should) be recast to the data type of
the array.
int nd
An integer providing the number of dimensions for this array. When nd is 0, the array is sometimes called a
rank-0 array. Such arrays have undefined dimensions and strides and cannot be accessed. NPY_MAXDIMS is
the largest number of dimensions for any array.
npy_intp dimensions
An array of integers providing the shape in each dimension as long as nd 1. The integer is always large
enough to hold a pointer on the platform, so the dimension size is only limited by memory.
npy_intp strides
An array of integers providing for each dimension the number of bytes that must be skipped to get to the next
element in that dimension.
PyObject base
This member is used to hold a pointer to another Python object that is related to this array. There are two use
cases: 1) If this array does not own its own memory, then base points to the Python object that owns it (perhaps
another array object), 2) If this array has the NPY_UPDATEIFCOPY flag set, then this array is a working copy
of a misbehaved array. As soon as this array is deleted, the array pointed to by base will be updated with the
contents of this array.
PyArray_Descr descr
A pointer to a data-type descriptor object (see below). The data-type descriptor object is an instance of a new
built-in type which allows a generic description of memory. There is a descriptor structure for each data type
supported. This descriptor structure contains useful information about the type as well as a pointer to a table of
function pointers to implement specific functionality.
int flags
Flags indicating how the memory pointed to by data is to be interpreted. Possible flags are
NPY_C_CONTIGUOUS, NPY_F_CONTIGUOUS, NPY_OWNDATA, NPY_ALIGNED, NPY_WRITEABLE,
and NPY_UPDATEIFCOPY.
PyObject weakreflist
This member allows array objects to have weak references (using the weakref module).
PyArrayDescr_Type
PyArrayDescr_Type
The PyArrayDescr_Type is the built-in type of the data-type-descriptor objects used to describe how the
bytes comprising the array are to be interpreted. There are 21 statically-defined PyArray_Descr objects
for the built-in data-types. While these participate in reference counting, their reference count should never
reach zero. There is also a dynamic table of user-defined PyArray_Descr objects that is also main-
tained. Once a data-type-descriptor object is registered it should never be deallocated either. The function
PyArray_DescrFromType (...) can be used to retrieve a PyArray_Descr object from an enumerated
type-number (either built-in or user- defined).
PyArray_Descr
The format of the PyArray_Descr structure that lies at the heart of the PyArrayDescr_Type is
typedef struct {
PyObject_HEAD
PyTypeObject *typeobj;
char kind;
char type;
char byteorder;
char unused;
int flags;
int type_num;
int elsize;
int alignment;
PyArray_ArrayDescr *subarray;
PyObject *fields;
PyArray_ArrFuncs *f;
} PyArray_Descr;
PyTypeObject typeobj
Pointer to a typeobject that is the corresponding Python type for the elements of this array. For the builtin
types, this points to the corresponding array scalar. For user-defined types, this should point to a user-defined
typeobject. This typeobject can either inherit from array scalars or not. If it does not inherit from array scalars,
then the NPY_USE_GETITEM and NPY_USE_SETITEM flags should be set in the flags member.
char kind
A character code indicating the kind of array (using the array interface typestring notation). A b represents
Boolean, a i represents signed integer, a u represents unsigned integer, f represents floating point, c
represents complex floating point, S represents 8-bit character string, U represents 32-bit/character unicode
string, and V repesents arbitrary.
char type
A traditional character code indicating the data type.
char byteorder
A character indicating the byte-order: > (big-endian), < (little- endian), = (native), | (irrelevant, ignore).
All builtin data- types have byteorder =.
int flags
A data-type bit-flag that determines if the data-type exhibits object- array like behavior. Each bit in this member
is a flag which are named as:
NPY_ITEM_REFCOUNT
NPY_ITEM_HASOBJECT
Indicates that items of this data-type must be reference counted (using Py_INCREF and Py_DECREF ).
NPY_ITEM_LISTPICKLE
Indicates arrays of this data-type must be converted to a list before pickling.
NPY_ITEM_IS_POINTER
Indicates the item is a pointer to some other data-type
NPY_NEEDS_INIT
Indicates memory for this data-type must be initialized (set to 0) on creation.
NPY_NEEDS_PYAPI
Indicates this data-type requires the Python C-API during access (so dont give up the GIL if array access
is going to be needed).
NPY_USE_GETITEM
On array access use the f->getitem function pointer instead of the standard conversion to an array
scalar. Must use if you dont define an array scalar to go along with the data-type.
NPY_USE_SETITEM
When creating a 0-d array from an array scalar use f->setitem instead of the standard copy from an
array scalar. Must use if you dont define an array scalar to go along with the data-type.
NPY_FROM_FIELDS
The bits that are inherited for the parent data-type if these bits are set in any field of the data-type. Cur-
rently ( NPY_NEEDS_INIT | NPY_LIST_PICKLE | NPY_ITEM_REFCOUNT | NPY_NEEDS_PYAPI
).
NPY_OBJECT_DTYPE_FLAGS
Bits set for the object data-type: ( NPY_LIST_PICKLE | NPY_USE_GETITEM |
NPY_ITEM_IS_POINTER | NPY_REFCOUNT | NPY_NEEDS_INIT | NPY_NEEDS_PYAPI).
PyDataType_FLAGCHK(PyArray_Descr *dtype, int flags)
Return true if all the given flags are set for the data-type object.
PyDataType_REFCHK(PyArray_Descr *dtype)
Equivalent to PyDataType_FLAGCHK (dtype, NPY_ITEM_REFCOUNT).
int type_num
A number that uniquely identifies the data type. For new data-types, this number is assigned when the data-type
is registered.
int elsize
For data types that are always the same size (such as long), this holds the size of the data type. For flexible data
types where different arrays can have a different elementsize, this should be 0.
int alignment
A number providing alignment information for this data type. Specifically, it shows how far from the start
of a 2-element structure (whose first element is a char ), the compiler places an item of this type:
offsetof(struct {char c; type v;}, v)
PyArray_ArrayDescr subarray
If this is non- NULL, then this data-type descriptor is a C-style contiguous array of another data-type descriptor.
In other-words, each element that this descriptor describes is actually an array of some other base descriptor.
This is most useful as the data-type descriptor for a field in another data-type descriptor. The fields member
should be NULL if this is non- NULL (the fields member of the base descriptor can be non- NULL however).
The PyArray_ArrayDescr structure is defined using
typedef struct {
PyArray_Descr *base;
PyObject *shape;
} PyArray_ArrayDescr;
typedef struct {
PyArray_VectorUnaryFunc *cast[PyArray_NTYPES];
PyArray_GetItemFunc *getitem;
PyArray_SetItemFunc *setitem;
PyArray_CopySwapNFunc *copyswapn;
PyArray_CopySwapFunc *copyswap;
PyArray_CompareFunc *compare;
PyArray_ArgFunc *argmax;
PyArray_DotFunc *dotfunc;
PyArray_ScanFunc *scanfunc;
PyArray_FromStrFunc *fromstr;
PyArray_NonzeroFunc *nonzero;
PyArray_FillFunc *fill;
PyArray_FillWithScalarFunc *fillwithscalar;
PyArray_SortFunc *sort[PyArray_NSORTS];
PyArray_ArgSortFunc *argsort[PyArray_NSORTS];
PyObject *castdict;
PyArray_ScalarKindFunc *scalarkind;
int **cancastscalarkindto;
int *cancastto;
int listpickle
} PyArray_ArrFuncs;
The concept of a behaved segment is used in the description of the function pointers. A behaved segment is one
that is aligned and in native machine byte-order for the data-type. The nonzero, copyswap, copyswapn,
getitem, and setitem functions can (and must) deal with mis-behaved arrays. The other functions require
behaved memory segments.
void cast(void *from, void *to, npy_intp n, void *fromarr,
void *toarr)
An array of function pointers to cast from the current type to all of the other builtin types. Each
function casts a contiguous, aligned, and notswapped buffer pointed at by from to a contiguous,
aligned, and notswapped buffer pointed at by to The number of items to cast is given by n, and the
arguments fromarr and toarr are interpreted as PyArrayObjects for flexible arrays to get itemsize
information.
PyObject getitem
A pointer to a function that returns a standard Python object from a single element of the array object arr
pointed to by data. This function must be able to deal with misbehaved (misaligned and/or swapped)
arrays correctly.
int setitem
A pointer to a function that sets the Python object item into the array, arr, at the position pointed to by data
. This function deals with misbehaved arrays. If successful, a zero is returned, otherwise, a negative one
is returned (and a Python error set).
void copyswapn(void *dest, npy_intp dstride, void *src,
void copyswap
These members are both pointers to functions to copy data from src to dest and swap if indicated. The
value of arr is only used for flexible ( NPY_STRING, NPY_UNICODE, and NPY_VOID ) arrays (and is
obtained from arr->descr->elsize ). The second function copies a single value, while the first
loops over n values with the provided strides. These functions can deal with misbehaved src data. If src is
NULL then no copy is performed. If swap is 0, then no byteswapping occurs. It is assumed that dest and
src do not overlap. If they overlap, then use memmove (...) first followed by copyswap(n) with NULL
valued src.
int compare
A pointer to a function that compares two elements of the array, arr, pointed to by d1 and d2. This
function requires behaved arrays. The return value is 1 if * d1 > * d2, 0 if * d1 == * d2, and -1 if * d1 <
* d2. The array object arr is used to retrieve itemsize and field information for flexible arrays.
int argmax(void* data, npy_intp n, npy_intp* max_ind,
void* arr)
A pointer to a function that retrieves the index of the largest of n elements in arr beginning at the
element pointed to by data. This function requires that the memory segment be contiguous and
behaved. The return value is always 0. The index of the largest element is returned in max_ind.
void dotfunc(void* ip1, npy_intp is1, void* ip2, npy_intp is2,
A pointer to a function that multiplies two n -length sequences together, adds them, and places
the result in element pointed to by op of arr. The start of the two sequences are pointed to by
ip1 and ip2. To get to the next element in each sequence requires a jump of is1 and is2
bytes, respectively. This function requires behaved (though not necessarily contiguous) memory.
int scanfunc
A pointer to a function that scans (scanf style) one element of the corresponding type from the file de-
scriptor fd into the array memory pointed to by ip. The array is assumed to be behaved. If sep is not
NULL, then a separator string is also scanned from the file before returning. The last argument arr is the
array to be scanned into. A 0 is returned if the scan is successful. A negative number indicates something
went wrong: -1 means the end of file was reached before the separator string could be scanned, -4 means
that the end of file was reached before the element could be scanned, and -3 means that the element could
not be interpreted from the format string. Requires a behaved array.
int fromstr
A pointer to a function that converts the string pointed to by str to one element of the corresponding
type and places it in the memory location pointed to by ip. After the conversion is completed, *endptr
points to the rest of the string. The last argument arr is the array into which ip points (needed for
variable-size data- types). Returns 0 on success or -1 on failure. Requires a behaved array.
Bool nonzero
A pointer to a function that returns TRUE if the item of arr pointed to by data is nonzero. This function
can deal with misbehaved arrays.
void fill
A pointer to a function that fills a contiguous array of given length with data. The first two elements of
the array must already be filled- in. From these two values, a delta will be computed and the values from
item 3 to the end will be computed by repeatedly adding this computed delta. The data buffer must be
well-behaved.
void fillwithscalar(void* buffer, npy_intp length,
A pointer to a function that fills a contiguous buffer of the given length with a single scalar
value whose address is given. The final argument is the array which is needed to get the
itemsize for variable-length arrays.
int sort
An array of function pointers to a particular sorting algorithms. A particular sorting algorithm is obtained
void *arr)
An array of function pointers to sorting algorithms for this data type. The same sorting algorithms
as for sort are available. The indices producing the sort are returned in result (which must be
initialized with indices 0 to length-1 inclusive).
PyObject castdict
Either NULL or a dictionary containing low-level casting functions for user- defined data-types. Each
function is wrapped in a PyCObject * and keyed by the data-type number.
PyArray_SCALARKIND scalarkind
A function to determine how scalars of this type should be interpreted. The argument is NULL or a
0-dimensional array containing the data (if that is needed to determine the kind of scalar). The return
value must be of type PyArray_SCALARKIND.
int cancastscalarkindto
Either NULL or an array of PyArray_NSCALARKINDS pointers. These pointers should each be either
NULL or a pointer to an array of integers (terminated by PyArray_NOTYPE) indicating data-types that
a scalar of this data-type of the specified kind can be cast to safely (this usually means without losing
precision).
int cancastto
Either NULL or an array of integers (terminated by PyArray_NOTYPE ) indicated data-types that this
data-type can be cast to safely (this usually means without losing precision).
int listpickle
Unused.
The PyArray_Type typeobject implements many of the features of Python objects including the tp_as_number,
tp_as_sequence, tp_as_mapping, and tp_as_buffer interfaces. The rich comparison (tp_richcompare) is also used
along with new-style attribute lookup for methods (tp_methods) and properties (tp_getset). The PyArray_Type can
also be sub-typed.
Tip: The tp_as_number methods use a generic approach to call whatever function has been registered for handling
the operation. The function PyNumeric_SetOps(..) can be used to register functions to handle particular mathematical
operations (for all arrays). When the umath module is imported, it sets the numeric operations for all arrays to the
corresponding ufuncs. The tp_str and tp_repr methods can also be altered using PyString_SetStringFunction(...).
PyUFunc_Type
PyUFunc_Type
The ufunc object is implemented by creation of the PyUFunc_Type. It is a very simple type that implements
only basic getattribute behavior, printing behavior, and has call behavior which allows these objects to act
like functions. The basic idea behind the ufunc is to hold a reference to fast 1-dimensional (vector) loops for
each data type that supports the operation. These one-dimensional loops all have the same signature and are
the key to creating a new ufunc. They are called by the generic looping code as appropriate to implement the
N-dimensional function. There are also some generic 1-d loops defined for floating and complexfloating arrays
that allow you to define a ufunc using a single scalar function (e.g. atanh).
PyUFuncObject
The core of the ufunc is the PyUFuncObject which contains all the information needed to call the underlying
C-code loops that perform the actual work. It has the following structure:
typedef struct {
PyObject_HEAD
int nin;
int nout;
int nargs;
int identity;
PyUFuncGenericFunction *functions;
void **data;
int ntypes;
int check_return;
char *name;
char *types;
char *doc;
void *ptr;
PyObject *obj;
PyObject *userloops;
} PyUFuncObject;
PyObject_HEAD
required for all Python objects.
int nin
The number of input arguments.
int nout
The number of output arguments.
int nargs
The total number of arguments (nin + nout). This must be less than NPY_MAXARGS.
int identity
Either PyUFunc_One, PyUFunc_Zero, or PyUFunc_None to indicate the identity for this operation.
It is only used for a reduce-like call on an empty array.
void PyUFuncObject.functions(char** args, npy_intp* dims,
An array of function pointers one for each data type supported by the ufunc. This is the vector
loop that is called to implement the underlying function dims [0] times. The first argument, args,
is an array of nargs pointers to behaved memory. Pointers to the data for the input arguments
are first, followed by the pointers to the data for the output arguments. How many bytes must be
skipped to get to the next element in the sequence is specified by the corresponding entry in the
steps array. The last argument allows the loop to receive extra information. This is commonly
used so that a single, generic vector loop can be used for multiple functions. In this case, the
actual scalar function to call is passed in as extradata. The size of this function pointer array is
ntypes.
void data
Extra data to be passed to the 1-d vector loops or NULL if no extra-data is needed. This C-array must be
the same size ( i.e. ntypes) as the functions array. NULL is used if extra_data is not needed. Several C-API
calls for UFuncs are just 1-d vector loops that make use of this extra data to receive a pointer to the actual
function to call.
int ntypes
The number of supported data types for the ufunc. This number specifies how many different 1-d loops
(of the builtin data types) are available.
int check_return
Obsolete and unused. However, it is set by the corresponding entry in the main ufunc creation routine:
PyUFunc_FromFuncAndData (...).
char name
A string name for the ufunc. This is used dynamically to build the __doc__ attribute of ufuncs.
char types
An array of nargs ntypes 8-bit type_numbers which contains the type signature for the function for
each of the supported (builtin) data types. For each of the ntypes functions, the corresponding set of type
numbers in this array shows how the args argument should be interpreted in the 1-d vector loop. These
type numbers do not have to be the same type and mixed-type ufuncs are supported.
char doc
Documentation for the ufunc. Should not contain the function signature as this is generated dynamically
when __doc__ is retrieved.
void ptr
Any dynamically allocated memory. Currently, this is used for dynamic ufuncs created from a python
function to store room for the types, data, and name members.
PyObject obj
For ufuncs dynamically created from python functions, this member holds a reference to the underlying
Python function.
PyObject userloops
A dictionary of user-defined 1-d vector loops (stored as CObject ptrs) for user-defined types. A loop may
be registered by the user for any user-defined type. It is retrieved by type number. User defined type
numbers are always larger than NPY_USERDEF.
PyArrayIter_Type
PyArrayIter_Type
This is an iterator object that makes it easy to loop over an N-dimensional array. It is the object returned from
the flat attribute of an ndarray. It is also used extensively throughout the implementation internals to loop
over an N-dimensional array. The tp_as_mapping interface is implemented so that the iterator object can be
indexed (using 1-d indexing), and a few methods are implemented through the tp_methods table. This object
implements the next method and can be used anywhere an iterator can be used in Python.
PyArrayIterObject
The C-structure corresponding to an object of PyArrayIter_Type is the PyArrayIterObject. The
PyArrayIterObject is used to keep track of a pointer into an N-dimensional array. It contains associated
information used to quickly march through the array. The pointer can be adjusted in three basic ways:
1) advance to the next position in the array in a C-style contiguous fashion, 2) advance to an arbitrary
N-dimensional coordinate in the array, and 3) advance to an arbitrary one-dimensional index into the array. The
members of the PyArrayIterObject structure are used in these calculations. Iterator objects keep their
own dimension and strides information about an array. This can be adjusted as needed for broadcasting, or to
loop over only specific dimensions.
typedef struct {
PyObject_HEAD
int nd_m1;
npy_intp index;
npy_intp size;
npy_intp coordinates[NPY_MAXDIMS];
npy_intp dims_m1[NPY_MAXDIMS];
npy_intp strides[NPY_MAXDIMS];
npy_intp backstrides[NPY_MAXDIMS];
npy_intp factors[NPY_MAXDIMS];
PyArrayObject *ao;
char *dataptr;
Bool contiguous;
} PyArrayIterObject;
int nd_m1
N 1 where N is the number of dimensions in the underlying array.
npy_intp index
The current 1-d index into the array.
npy_intp size
The total size of the underlying array.
npy_intp coordinates
An N -dimensional index into the array.
npy_intp dims_m1
The size of the array minus 1 in each dimension.
npy_intp strides
The strides of the array. How many bytes needed to jump to the next element in each dimension.
npy_intp backstrides
How many bytes needed to jump from the end of a dimension back to its beginning. Note that backstrides
[k]= strides [k]*d ims_m1 [k], but it is stored here as an optimization.
npy_intp factors
This array is used in computing an N-d index from a 1-d index. It contains needed products of the dimen-
sions.
PyArrayObject ao
A pointer to the underlying ndarray this iterator was created to represent.
char dataptr
This member points to an element in the ndarray indicated by the index.
Bool contiguous
This flag is true if the underlying array is NPY_C_CONTIGUOUS. It is used to simplify calculations when
possible.
How to use an array iterator on a C-level is explained more fully in later sections. Typically, you do not need to
concern yourself with the internal structure of the iterator object, and merely interact with it through the use of the
macros PyArray_ITER_NEXT (it), PyArray_ITER_GOTO (it, dest), or PyArray_ITER_GOTO1D (it, index).
All of these macros require the argument it to be a PyArrayIterObject *.
PyArrayMultiIter_Type
PyArrayMultiIter_Type
This type provides an iterator that encapsulates the concept of broadcasting. It allows N arrays to be broadcast
together so that the loop progresses in C-style contiguous fashion over the broadcasted array. The corresponding
C-structure is the PyArrayMultiIterObject whose memory layout must begin any object, obj, passed in
to the PyArray_Broadcast (obj) function. Broadcasting is performed by adjusting array iterators so that
each iterator represents the broadcasted shape and size, but has its strides adjusted so that the correct element
from the array is used at each iteration.
PyArrayMultiIterObject
typedef struct {
PyObject_HEAD
int numiter;
npy_intp size;
npy_intp index;
int nd;
npy_intp dimensions[NPY_MAXDIMS];
PyArrayIterObject *iters[NPY_MAXDIMS];
} PyArrayMultiIterObject;
PyObject_HEAD
Needed at the start of every Python object (holds reference count and type identification).
int numiter
The number of arrays that need to be broadcast to the same shape.
npy_intp size
The total broadcasted size.
npy_intp index
The current (1-d) index into the broadcasted result.
int nd
The number of dimensions in the broadcasted result.
npy_intp dimensions
The shape of the broadcasted result (only nd slots are used).
PyArrayIterObject iters
An array of iterator objects that holds the iterators for the arrays to be broadcast together. On return, the
iterators are adjusted for broadcasting.
PyArrayNeighborhoodIter_Type
PyArrayNeighborhoodIter_Type
This is an iterator object that makes it easy to loop over an N-dimensional neighborhood.
PyArrayNeighborhoodIterObject
The C-structure corresponding to an object of PyArrayNeighborhoodIter_Type is the
PyArrayNeighborhoodIterObject.
PyArrayFlags_Type
PyArrayFlags_Type
When the flags attribute is retrieved from Python, a special builtin object of this type is constructed. This special
type makes it easier to work with the different flags by accessing them as attributes or by accessing them as if
the object were a dictionary with the flag names as entries.
ScalarArrayTypes
There is a Python type for each of the different built-in data types that can be present in the array Most of these are sim-
ple wrappers around the corresponding data type in C. The C-names for these types are Py{TYPE}ArrType_Type
where {TYPE} can be
Bool, Byte, Short, Int, Long, LongLong, UByte, UShort, UInt, ULong, ULongLong, Float, Double,
LongDouble, CFloat, CDouble, CLongDouble, String, Unicode, Void, and Object.
These type names are part of the C-API and can therefore be created in extension C-code. There is also a
PyIntpArrType_Type and a PyUIntpArrType_Type that are simple substitutes for one of the integer types
that can hold a pointer on the platform. The structure of these scalar objects is not exposed to C-code. The function
PyArray_ScalarAsCtype (..) can be used to extract the C-type value from the array scalar and the function
PyArray_Scalar (...) can be used to construct an array scalar from a C-value.
A few new C-structures were found to be useful in the development of NumPy. These C-structures are used in at least
one C-API call and are therefore documented here. The main reason these structures were defined is to make it easy
to use the Python ParseTuple C-API to convert from Python objects to a useful C-Object.
PyArray_Dims
PyArray_Dims
This structure is very useful when shape and/or strides information is supposed to be interpreted. The structure
is:
typedef struct {
npy_intp *ptr;
int len;
} PyArray_Dims;
PyArray_Chunk
PyArray_Chunk
This is equivalent to the buffer object structure in Python up to the ptr member. On 32-bit platforms (i.e. if
NPY_SIZEOF_INT == NPY_SIZEOF_INTP ) or in Python 2.5, the len member also matches an equivalent
member of the buffer object. It is useful to represent a generic single- segment chunk of memory.
typedef struct {
PyObject_HEAD
PyObject *base;
void *ptr;
npy_intp len;
int flags;
} PyArray_Chunk;
PyObject base
The Python object this chunk of memory comes from. Needed so that memory can be accounted for
properly.
void ptr
A pointer to the start of the single-segment chunk of memory.
npy_intp len
The length of the segment in bytes.
int flags
Any data flags (e.g. NPY_WRITEABLE ) that should be used to interpret the memory.
PyArrayInterface
See Also:
The Array Interface
PyArrayInterface
The PyArrayInterface structure is defined so that NumPy and other extension modules can use the rapid
array interface protocol. The __array_struct__ method of an object that supports the rapid array interface
protocol should return a PyCObject that contains a pointer to a PyArrayInterface structure with the
relevant details of the array. After the new array is created, the attribute should be DECREFd which will
free the PyArrayInterface structure. Remember to INCREF the object (whose __array_struct__
attribute was retrieved) and point the base member of the new PyArrayObject to this same object. In this
way the memory for the array will be managed correctly.
typedef struct {
int two;
int nd;
char typekind;
int itemsize;
int flags;
npy_intp *shape;
npy_intp *strides;
void *data;
PyObject *descr;
} PyArrayInterface;
int two
the integer 2 as a sanity check.
int nd
the number of dimensions in the array.
char typekind
A character indicating what kind of array is present according to the typestring convention with t ->
bitfield, b -> Boolean, i -> signed integer, u -> unsigned integer, f -> floating point, c -> complex
floating point, O -> object, S -> string, U -> unicode, V -> void.
int itemsize
The number of bytes each item in the array requires.
int flags
Any of the bits NPY_C_CONTIGUOUS (1), NPY_F_CONTIGUOUS (2), NPY_ALIGNED (0x100),
NPY_NOTSWAPPED (0x200), or NPY_WRITEABLE (0x400) to indicate something about the data. The
NPY_ALIGNED, NPY_C_CONTIGUOUS, and NPY_F_CONTIGUOUS flags can actually be determined
from the other parameters. The flag NPY_ARR_HAS_DESCR (0x800) can also be set to indicate to
objects consuming the version 3 array interface that the descr member of the structure is present (it will
be ignored by objects consuming version 2 of the array interface).
npy_intp shape
An array containing the size of the array in each dimension.
npy_intp strides
An array containing the number of bytes to jump to get to the next element in each dimension.
void data
A pointer to the first element of the array.
PyObject descr
A Python object describing the data-type in more detail (same as the descr key in
__array_interface__). This can be NULL if typekind and itemsize provide enough informa-
tion. This field is also ignored unless ARR_HAS_DESCR flag is on in flags.
Internally, the code uses some additional Python objects primarily for memory management. These types are not
accessible directly from Python, and are not exposed to the C-API. They are included here only for completeness and
assistance in understanding the code.
PyUFuncLoopObject
A loose wrapper for a C-structure that contains the information needed for looping. This is useful if you are
trying to understand the ufunc looping code. The PyUFuncLoopObject is the associated C-structure. It is
defined in the ufuncobject.h header.
PyUFuncReduceObject
A loose wrapper for the C-structure that contains the information needed for reduce-like methods of
ufuncs. This is useful if you are trying to understand the reduce, accumulate, and reduce-at code. The
PyUFuncReduceObject is the associated C-structure. It is defined in the ufuncobject.h header.
PyUFunc_Loop1d
A simple linked-list of C-structures containing the information needed to define a 1-d loop for a ufunc for every
defined signature of a user-defined data-type.
PyArrayMapIter_Type
Advanced indexing is handled with this Python type. It is simply a loose wrapper around the C-
structure containing the variables needed for advanced array indexing. The associated C-structure,
PyArrayMapIterObject, is useful if you are trying to understand the advanced-index mapping
code. It is defined in the arrayobject.h header. This type is not exposed to Python and could be replaced
with a C-structure. As a Python type it takes advantage of reference- counted memory management.
When NumPy is built, information about system configuration is recorded, and is made available for extension modules
using Numpys C API. These are mostly defined in numpyconfig.h (included in ndarrayobject.h). The
public symbols are prefixed by NPY_*. Numpy also offers some functions for querying information about the platform
in use.
For private use, Numpy also constructs a config.h in the NumPy include directory, which is not exported by Numpy
(that is a python extension which use the numpy C API will not see those symbols), to avoid namespace pollution.
The NPY_SIZEOF_{CTYPE} constants are defined so that sizeof information is available to the pre-processor.
NPY_SIZEOF_SHORT
sizeof(short)
NPY_SIZEOF_INT
sizeof(int)
NPY_SIZEOF_LONG
sizeof(long)
NPY_SIZEOF_LONG_LONG
sizeof(longlong) where longlong is defined appropriately on the platform (A macro defines
NPY_SIZEOF_LONGLONG as well.)
NPY_SIZEOF_PY_LONG_LONG
NPY_SIZEOF_FLOAT
sizeof(float)
NPY_SIZEOF_DOUBLE
sizeof(double)
NPY_SIZEOF_LONG_DOUBLE
sizeof(longdouble) (A macro defines NPY_SIZEOF_LONGDOUBLE as well.)
NPY_SIZEOF_PY_INTPTR_T
Size of a pointer on this platform (sizeof(void *)) (A macro defines NPY_SIZEOF_INTP as well.)
NPY_CPU_X86
NPY_CPU_AMD64
NPY_CPU_IA64
NPY_CPU_PPC
NPY_CPU_PPC64
NPY_CPU_SPARC
NPY_CPU_SPARC64
NPY_CPU_S390
NPY_CPU_PARISC
New in version 1.3.0. CPU architecture of the platform; only one of the above is defined.
Defined in numpy/npy_cpu.h
NPY_LITTLE_ENDIAN
NPY_BIG_ENDIAN
NPY_BYTE_ORDER
New in version 1.3.0. Portable alternatives to the endian.h macros of GNU Libc. If big endian,
NPY_BYTE_ORDER == NPY_BIG_ENDIAN, and similarly for little endian architectures.
Defined in numpy/npy_endian.h.
PyArray_GetEndianness()
New in version 1.3.0. Returns the endianness of the current platform. One of NPY_CPU_BIG,
NPY_CPU_LITTLE, or NPY_CPU_UNKNOWN_ENDIAN.
The standard array can have 21 different data types (and has some support for adding your own types). These data
types all have an enumerated type, an enumerated type-character, and a corresponding array scalar Python type object
(placed in a hierarchy). There are also standard C typedefs to make it easier to manipulate elements of the given data
type. For the numeric types, there are also bit-width equivalent C typedefs and named typenumbers that make it easier
to select the precision desired.
Warning: The names for the types in c code follows c naming conventions more closely. The Python names for
these types follow Python conventions. Thus, NPY_FLOAT picks up a 32-bit float in C, but numpy.float_ in
Python corresponds to a 64-bit double. The bit-width names can be used in both Python and C for clarity.
There is a list of enumerated types defined providing the basic 21 data types plus some useful generic names. Whenever
the code requires a type number, one of these enumerated types is requested. The types are all called NPY_{NAME}
where {NAME} can be
BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONG-
LONG, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE, CLONGDOUBLE, OBJECT,
STRING, UNICODE, VOID
NTYPES, NOTYPE, USERDEF, DEFAULT_TYPE
The various character codes indicating certain types are also part of an enumerated list. References to type characters
(should they be needed at all) should always use these enumerations. The form of them is NPY_{NAME}LTR where
{NAME} can be
BOOL, BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG, ULONG, LONGLONG, ULONG-
LONG, FLOAT, DOUBLE, LONGDOUBLE, CFLOAT, CDOUBLE, CLONGDOUBLE, OBJECT,
STRING, VOID
INTP, UINTP
GENBOOL, SIGNED, UNSIGNED, FLOATING, COMPLEX
The latter group of {NAME}s corresponds to letters used in the array interface typestring specification.
5.3.2 Defines
NPY_MAX_INT{bits}
NPY_MAX_UINT{bits}
NPY_MIN_INT{bits}
These are defined for {bits} = 8, 16, 32, 64, 128, and 256 and provide the maximum (minimum) value of the
corresponding (unsigned) integer type. Note: the actual integer type may not be available on all platforms (i.e.
128-bit and 256-bit integers are rare).
NPY_MIN_{type}
This is defined for {type} = BYTE, SHORT, INT, LONG, LONGLONG, INTP
NPY_MAX_{type}
This is defined for all defined for {type} = BYTE, UBYTE, SHORT, USHORT, INT, UINT, LONG,
ULONG, LONGLONG, ULONGLONG, INTP, UINTP
All of the numeric data types (integer, floating point, and complex) have constants that are defined to be a specific
enumerated type number. Exactly which enumerated type a bit-width type refers to is platform dependent. In partic-
ular, the constants available are PyArray_{NAME}{BITS} where {NAME} is INT, UINT, FLOAT, COMPLEX
and {BITS} can be 8, 16, 32, 64, 80, 96, 128, 160, 192, 256, and 512. Obviously not all bit-widths are available on
all platforms for all the kinds of numeric types. Commonly 8-, 16-, 32-, 64-bit integers; 32-, 64-bit floats; and 64-,
128-bit complex types are available.
The constants PyArray_INTP and PyArray_UINTP refer to an enumerated integer type that is large enough to hold
a pointer on the platform. Index arrays should always be converted to PyArray_INTP , because the dimension of the
array is of type npy_intp.
There are standard variable types for each of the numeric data types and the bool data type. Some of these are already
available in the C-specification. You can create variables in extension code with these types.
Boolean
npy_bool
unsigned char; The constants NPY_FALSE and NPY_TRUE are also defined.
(Un)Signed Integer
Unsigned versions of the integers can be defined by pre-pending a u to the front of the integer name.
npy_(u)byte
(unsigned) char
npy_(u)short
(unsigned) short
npy_(u)int
(unsigned) int
npy_(u)long
(unsigned) long int
npy_(u)longlong
(unsigned long long int)
npy_(u)intp
(unsigned) Py_intptr_t (an integer that is the size of a pointer on the platform).
npy_(c)float
float
npy_(c)double
double
npy_(c)longdouble
long double
complex types are structures with .real and .imag members (in that order).
Bit-width names
There are also typedefs for signed integers, unsigned integers, floating point, and complex floating point types of
specific bit- widths. The available type names are
npy_int{bits}, npy_uint{bits}, npy_float{bits}, and npy_complex{bits}
where {bits} is the number of bits in the type and can be 8, 16, 32, 64, 128, and 256 for integer types; 16, 32 , 64,
80, 96, 128, and 256 for floating-point types; and 32, 64, 128, 160, 192, and 512 for complex-valued types. Which
bit-widths are available is platform dependent. The bolded bit-widths are usually available on all platforms.
For help in printing, the following strings are defined as the correct format specifier in printf and related commands.
NPY_LONGLONG_FMT, NPY_ULONGLONG_FMT, NPY_INTP_FMT, NPY_UINTP_FMT,
NPY_LONGDOUBLE_FMT
These macros all access the PyArrayObject structure members. The input argument, obj, can be any PyObject
* that is directly interpretable as a PyArrayObject * (any instance of the PyArray_Type and its sub-types).
void * PyArray_DATA(PyObject *obj)
Data access
These functions and macros provide easy access to elements of the ndarray from C. These work for all arrays. You
may need to take care when accessing the data in the array, however, if it is not in machine byte-order, misaligned, or
not writeable. In other words, be sure to respect the state of the flags unless you know what you are doing, or have
previously guaranteed an array that is writeable, aligned, and in machine byte-order using PyArray_FromAny. If
you wish to handle all types of arrays, the copyswap function for each type is useful for handling misbehaved arrays.
Some platforms (e.g. Solaris) do not like misaligned data and will crash if you de-reference a misaligned pointer.
Other platforms (e.g. x86 Linux) will just work more slowly with misaligned data.
void* PyArray_GetPtr(PyArrayObject* aobj, npy_intp* ind)
Return a pointer to the data of the ndarray, aobj, at the N-dimensional index given by the c-array, ind, (which
must be at least aobj ->nd in size). You may want to typecast the returned pointer to the data type of the ndarray.
void* PyArray_GETPTR1(PyObject* obj, <npy_intp> i)
From scratch
PyObject* PyArray_New(PyTypeObject* subtype, int nd, npy_intp* dims, int type_num, npy_intp* strides,
void* data, int itemsize, int flags, PyObject* obj)
This is similar to PyArray_DescrNew (...) except you specify the data-type descriptor with type_num and
itemsize, where type_num corresponds to a builtin (or user-defined) type. If the type always has the same
number of bytes, then itemsize is ignored. Otherwise, itemsize specifies the particular size of this array.
Warning: If data is passed to PyArray_NewFromDescr or PyArray_New, this memory must not be deal-
located until the new array is deleted. If this data came from another Python object, this can be accomplished
using Py_INCREF on that object and setting the base member of the new array to point to that object. If strides
are passed in they must be consistent with the dimensions, the itemsize, and the data of the array.
PyObject* PyArray_FromAny(PyObject* op, PyArray_Descr* dtype, int min_depth, int max_depth, int re-
quirements, PyObject* context)
This is the main function used to obtain an array from any nested sequence, or object that exposes the array
interface, op. The parameters allow specification of the required dtype, the minimum (min_depth) and maximum
(max_depth) number of dimensions acceptable, and other requirements for the array. The dtype argument needs
to be a PyArray_Descr structure indicating the desired data-type (including required byteorder). The dtype
argument may be NULL, indicating that any data-type (and byteorder) is acceptable. Unless FORCECAST is
present in flags, this call will generate an error if the data type cannot be safely obtained from the object. If
you want to use NULL for the dtype and ensure the array is notswapped then use PyArray_CheckFromAny.
A value of 0 for either of the depth parameters causes the parameter to be ignored. Any of the following
array flags can be added (e.g. using |) to get the requirements argument. If your code can handle general (e.g.
strided, byte-swapped, or unaligned arrays) then requirements may be 0. Also, if op is not already an array (or
does not expose the array interface), then a new array will be created (and filled from op using the sequence
protocol). The new array will have NPY_DEFAULT as its flags member. The context argument is passed to the
__array__ method of op and is only used if the array is constructed that way. Almost always this parameter
is NULL.
NPY_C_CONTIGUOUS
Make sure the returned array is C-style contiguous
NPY_F_CONTIGUOUS
Make sure the returned array is Fortran-style contiguous.
NPY_ALIGNED
Make sure the returned array is aligned on proper boundaries for its data type. An aligned array has the
data pointer and every strides factor as a multiple of the alignment factor for the data-type- descriptor.
NPY_WRITEABLE
Make sure the returned array can be written to.
NPY_ENSURECOPY
Make sure a copy is made of op. If this flag is not present, data is not copied if it can be avoided.
NPY_ENSUREARRAY
Make sure the result is a base-class ndarray or bigndarray. By default, if op is an instance of a subclass of
the bigndarray, an instance of that same subclass is returned. If this flag is set, an ndarray object will be
returned instead.
NPY_FORCECAST
Force a cast to the output type even if it cannot be done safely. Without this flag, a data cast will occur
only if it can be done safely, otherwise an error is reaised.
NPY_UPDATEIFCOPY
If op is already an array, but does not satisfy the requirements, then a copy is made (which will satisfy the
requirements). If this flag is present and a copy (of an object that is already an array) must be made, then
the corresponding NPY_UPDATEIFCOPY flag is set in the returned copy and op is made to be read-only.
When the returned copy is deleted (presumably after your calculations are complete), its contents will be
copied back into op and the op array will be made writeable again. If op is not writeable to begin with,
then an error is raised. If op is not already an array, then this flag has no effect.
NPY_BEHAVED
NPY_ALIGNED | NPY_WRITEABLE
NPY_CARRAY
NPY_C_CONTIGUOUS | NPY_BEHAVED
NPY_CARRAY_RO
NPY_C_CONTIGUOUS | NPY_ALIGNED
NPY_FARRAY
NPY_F_CONTIGUOUS | NPY_BEHAVED
NPY_FARRAY_RO
NPY_F_CONTIGUOUS | NPY_ALIGNED
NPY_DEFAULT
NPY_CARRAY
NPY_IN_ARRAY
NPY_CONTIGUOUS | NPY_ALIGNED
NPY_IN_FARRAY
NPY_F_CONTIGUOUS | NPY_ALIGNED
NPY_INOUT_ARRAY
NPY_C_CONTIGUOUS | NPY_WRITEABLE | NPY_ALIGNED
NPY_INOUT_FARRAY
NPY_F_CONTIGUOUS | NPY_WRITEABLE | NPY_ALIGNED
NPY_OUT_ARRAY
NPY_C_CONTIGUOUS | NPY_WRITEABLE | NPY_ALIGNED | NPY_UPDATEIFCOPY
NPY_OUT_FARRAY
NPY_F_CONTIGUOUS | NPY_WRITEABLE | NPY_ALIGNED | UPDATEIFCOPY
PyObject* PyArray_CheckFromAny(PyObject* op, PyArray_Descr* dtype, int min_depth, int max_depth,
int requirements, PyObject* context)
Nearly identical to PyArray_FromAny (...) except requirements can contain NPY_NOTSWAPPED (over-
riding the specification in dtype) and NPY_ELEMENTSTRIDES which indicates that the array should be
aligned in the sense that the strides are multiples of the element size.
NPY_NOTSWAPPED
Make sure the returned array has a data-type descriptor that is in machine byte-order, over-riding any specifi-
cation in the dtype argument. Normally, the byte-order requirement is determined by the dtype argument. If
this flag is set and the dtype argument does not indicate a machine byte-order descriptor (or is NULL and the
object is already an array with a data-type descriptor that is not in machine byte- order), then a new data-type
descriptor is created and used with its byte-order field set to native.
NPY_BEHAVED_NS
NPY_ALIGNED | NPY_WRITEABLE | NPY_NOTSWAPPED
NPY_ELEMENTSTRIDES
Make sure the returned array has strides that are multiples of the element size.
PyObject* PyArray_FromArray(PyArrayObject* op, PyArray_Descr* newtype, int requirements)
Special case of PyArray_FromAny for when op is already an array but it needs to be of a specific newtype
(including byte-order) or has certain requirements.
PyObject* PyArray_FromStructInterface(PyObject* op)
Returns an ndarray object from a Python object that exposes the __array_struct__ method and fol-
lows the array interface protocol. If the object does not contain this method then a borrowed reference to
Py_NotImplemented is returned.
PyObject* PyArray_FromInterface(PyObject* op)
Returns an ndarray object from a Python object that exposes the __array_shape__ and
__array_typestr__ methods following the array interface protocol. If the object does not contain
one of these method then a borrowed reference to Py_NotImplemented is returned.
PyObject* PyArray_FromArrayAttr(PyObject* op, PyArray_Descr* dtype, PyObject* context)
Return an ndarray object from a Python object that exposes the __array__ method. The __array__
method can take 0, 1, or 2 arguments ([dtype, context]) where context is used to pass information about where
the __array__ method is being called from (currently only used in ufuncs).
PyObject* PyArray_ContiguousFromAny(PyObject* op, int typenum, int min_depth, int max_depth)
This function returns a (C-style) contiguous and behaved function array from any nested sequence or array
interface exporting object, op, of (non-flexible) type given by the enumerated typenum, of minimum depth
min_depth, and of maximum depth max_depth. Equivalent to a call to PyArray_FromAny with requirements
set to NPY_DEFAULT and the type_num member of the type argument set to typenum.
PyObject * PyArray_FromObject(PyObject *op, int typenum, int min_depth, int max_depth)
Return an aligned and in native-byteorder array from any nested sequence or array-interface exporting object,
op, of a type given by the enumerated typenum. The minimum number of dimensions the array can have is
given by min_depth while the maximum is max_depth. This is equivalent to a call to PyArray_FromAny
with requirements set to BEHAVED.
PyObject* PyArray_EnsureArray(PyObject* op)
This function steals a reference to op and makes sure that op is a base-class ndarray. It special cases array
scalars, but otherwise calls PyArray_FromAny ( op, NULL, 0, 0, NPY_ENSUREARRAY).
PyObject* PyArray_FromString(char* string, npy_intp slen, PyArray_Descr* dtype, npy_intp num, char*
sep)
Construct a one-dimensional ndarray of a single type from a binary or (ASCII) text string of length slen.
The data-type of the array to-be-created is given by dtype. If num is -1, then copy the entire string and return
an appropriately sized array, otherwise, num is the number of items to copy from the string. If sep is NULL
(or ), then interpret the string as bytes of binary data, otherwise convert the sub-strings separated by sep to
items of data-type dtype. Some data-types may not be readable in text mode and an error will be raised if that
occurs. All errors return NULL.
PyObject* PyArray_FromFile(FILE* fp, PyArray_Descr* dtype, npy_intp num, char* sep)
Construct a one-dimensional ndarray of a single type from a binary or text file. The open file pointer is fp, the
data-type of the array to be created is given by dtype. This must match the data in the file. If num is -1, then
read until the end of the file and return an appropriately sized array, otherwise, num is the number of items to
read. If sep is NULL (or ), then read from the file in binary mode, otherwise read from the file in text mode
with sep providing the item separator. Some array types cannot be read in text mode in which case an error is
raised.
PyObject* PyArray_FromBuffer(PyObject* buf, PyArray_Descr* dtype, npy_intp count, npy_intp offset)
Construct a one-dimensional ndarray of a single type from an object, buf, that exports the (single-segment)
buffer protocol (or has an attribute __buffer__ that returns an object that exports the buffer protocol). A
writeable buffer will be tried first followed by a read- only buffer. The NPY_WRITEABLE flag of the returned
array will reflect which one was successful. The data is assumed to start at offset bytes from the start of the
memory location for the object. The type of the data in the buffer will be interpreted depending on the data-
type descriptor, dtype. If count is negative then it will be determined from the size of the buffer and the
requested itemsize, otherwise, count represents how many elements should be converted from the buffer.
int PyArray_CopyInto(PyArrayObject* dest, PyArrayObject* src)
Copy from the source array, src, into the destination array, dest, performing a data-type conversion if neces-
sary. If an error occurs return -1 (otherwise 0). The shape of src must be broadcastable to the shape of dest.
The data areas of dest and src must not overlap.
int PyArray_MoveInto(PyArrayObject* dest, PyArrayObject* src)
Move data from the source array, src, into the destination array, dest, performing a data-type conversion if
necessary. If an error occurs return -1 (otherwise 0). The shape of src must be broadcastable to the shape of
dest. The data areas of dest and src may overlap.
PyArrayObject* PyArray_GETCONTIGUOUS(PyObject* op)
If op is already (C-style) contiguous and well-behaved then just return a reference, otherwise return a (contigu-
ous and well-behaved) copy of the array. The parameter op must be a (sub-class of an) ndarray and no checking
for that is done.
PyObject* PyArray_FROM_O(PyObject* obj)
Convert obj to an ndarray. The argument can be any nested sequence or object that exports the array interface.
This is a macro form of PyArray_FromAny using NULL, 0, 0, 0 for the other arguments. Your code must be
able to handle any data-type descriptor and any combination of data-flags to use this macro.
PyArray_Check(op)
Evaluates true if op is a Python object whose type is a sub-type of PyArray_Type.
PyArray_CheckExact(op)
Evaluates true if op is a Python object with type PyArray_Type.
PyArray_HasArrayInterface(op, out)
If op implements any part of the array interface, then out will contain a new reference to the newly created
ndarray using the interface or out will contain NULL if an error during conversion occurs. Otherwise, out will
contain a borrowed reference to Py_NotImplemented and no error condition is set.
PyArray_HasArrayInterfaceType(op, type, context, out)
If op implements any part of the array interface, then out will contain a new reference to the newly created
ndarray using the interface or out will contain NULL if an error during conversion occurs. Otherwise, out will
contain a borrowed reference to Py_NotImplemented and no error condition is set. This version allows setting
of the type and context in the part of the array interface that looks for the __array__ attribute.
PyArray_IsZeroDim(op)
Evaluates true if op is an instance of (a subclass of) PyArray_Type and has 0 dimensions.
PyArray_IsScalar(op, cls)
Evaluates true if op is an instance of Py{cls}ArrType_Type.
PyArray_CheckScalar(op)
Evaluates true if op is either an array scalar (an instance of a sub-type of PyGenericArr_Type ), or an
instance of (a sub-class of) PyArray_Type whose dimensionality is 0.
PyArray_IsPythonScalar(op)
Evaluates true if op is a builtin Python scalar object (int, float, complex, str, unicode, long, bool).
PyArray_IsAnyScalar(op)
Evaluates true if op is either a Python scalar or an array scalar (an instance of a sub- type of
PyGenericArr_Type ).
Data-type checking
For the typenum macros, the argument is an integer representing an enumerated array data type. For the array type
checking macros the argument must be a PyObject * that can be directly interpreted as a PyArrayObject *.
PyTypeNum_ISUNSIGNED(num)
PyDataType_ISUNSIGNED(descr)
PyArray_ISUNSIGNED(obj)
Type represents an unsigned integer.
PyTypeNum_ISSIGNED(num)
PyDataType_ISSIGNED(descr)
PyArray_ISSIGNED(obj)
Type represents a signed integer.
PyTypeNum_ISINTEGER(num)
PyDataType_ISINTEGER(descr)
PyArray_ISINTEGER(obj)
Type represents any integer.
PyTypeNum_ISFLOAT(num)
PyDataType_ISFLOAT(descr)
PyArray_ISFLOAT(obj)
Type represents any floating point number.
PyTypeNum_ISCOMPLEX(num)
PyDataType_ISCOMPLEX(descr)
PyArray_ISCOMPLEX(obj)
Type represents any complex floating point number.
PyTypeNum_ISNUMBER(num)
PyDataType_ISNUMBER(descr)
PyArray_ISNUMBER(obj)
Type represents any integer, floating point, or complex floating point number.
PyTypeNum_ISSTRING(num)
PyDataType_ISSTRING(descr)
PyArray_ISSTRING(obj)
Type represents a string data type.
PyTypeNum_ISPYTHON(num)
PyDataType_ISPYTHON(descr)
PyArray_ISPYTHON(obj)
Type represents an enumerated type corresponding to one of the standard Python scalar (bool, int, float, or
complex).
PyTypeNum_ISFLEXIBLE(num)
PyDataType_ISFLEXIBLE(descr)
PyArray_ISFLEXIBLE(obj)
Type represents one of the flexible array types ( NPY_STRING, NPY_UNICODE, or NPY_VOID ).
PyTypeNum_ISUSERDEF(num)
PyDataType_ISUSERDEF(descr)
PyArray_ISUSERDEF(obj)
Type represents a user-defined type.
PyTypeNum_ISEXTENDED(num)
PyDataType_ISEXTENDED(descr)
PyArray_ISEXTENDED(obj)
Type is either flexible or user-defined.
PyTypeNum_ISOBJECT(num)
PyDataType_ISOBJECT(descr)
PyArray_ISOBJECT(obj)
Type represents object data type.
PyTypeNum_ISBOOL(num)
PyDataType_ISBOOL(descr)
PyArray_ISBOOL(obj)
Type represents Boolean data type.
PyDataType_HASFIELDS(descr)
PyArray_HASFIELDS(obj)
Type has fields associated with it.
PyArray_ISNOTSWAPPED(m)
Evaluates true if the data area of the ndarray m is in machine byte-order according to the arrays data-type
descriptor.
PyArray_ISBYTESWAPPED(m)
Evaluates true if the data area of the ndarray m is not in machine byte-order according to the arrays data-type
descriptor.
Bool PyArray_EquivTypes(PyArray_Descr* type1, PyArray_Descr* type2)
Return NPY_TRUE if type1 and type2 actually represent equivalent types for this platform (the fortran member
of each type is ignored). For example, on 32-bit platforms, NPY_LONG and NPY_INT are equivalent.
Otherwise return NPY_FALSE.
Bool PyArray_EquivArrTypes(PyArrayObject* a1, PyArrayObject * a2)
Return NPY_TRUE if a1 and a2 are arrays with equivalent types for this platform.
Bool PyArray_EquivTypenums(int typenum1, int typenum2)
Special case of PyArray_EquivTypes (...) that does not accept flexible data types but may be easier to call.
int PyArray_EquivByteorders({byteorder} b1, {byteorder} b2)
True if byteorder characters ( NPY_LITTLE, NPY_BIG, NPY_NATIVE, NPY_IGNORE ) are either equal or
equivalent as to their specification of a native byte order. Thus, on a little-endian machine NPY_LITTLE and
NPY_NATIVE are equivalent where they are not equivalent on a big-endian machine.
void PyArray_InitArrFuncs(PyArray_ArrFuncs* f )
Initialize all function pointers and members to NULL.
int PyArray_RegisterDataType(PyArray_Descr* dtype)
Register a data-type as a new user-defined data type for arrays. The type must have most of its entries filled
in. This is not always checked and errors can produce segfaults. In particular, the typeobj member of the
dtype structure must be filled with a Python type that has a fixed-size element-size that corresponds to the
elsize member of dtype. Also the f member must have the required functions: nonzero, copyswap, copyswapn,
getitem, setitem, and cast (some of the cast functions may be NULL if no support is desired). To avoid
confusion, you should choose a unique character typecode but this is not enforced and not relied on internally.
A user-defined type number is returned that uniquely identifies the type. A pointer to the new structure can then
be obtained from PyArray_DescrFromType using the returned type number. A -1 is returned if an error
occurs. If this dtype has already been registered (checked only by the address of the pointer), then return the
previously-assigned type-number.
int PyArray_RegisterCastFunc(PyArray_Descr* descr, int totype, PyArray_VectorUnaryFunc* castfunc)
Register a low-level casting function, castfunc, to convert from the data-type, descr, to the given data-type
number, totype. Any old casting function is over-written. A 0 is returned on success or a -1 on failure.
int PyArray_RegisterCanCast(PyArray_Descr* descr, int totype, PyArray_SCALARKIND scalar)
Register the data-type number, totype, as castable from data-type object, descr, of the given scalar kind. Use
scalar = NPY_NOSCALAR to register that an array of data-type descr can be cast safely to a data-type whose
type_number is totype.
The flags attribute of the PyArrayObject structure contains important information about the memory used by
the array (pointed to by the data member) This flag information must be kept accurate or strange results and even
segfaults may result.
There are 6 (binary) flags that describe the memory area used by the data buffer. These constants are defined in
arrayobject.h and determine the bit-position of the flag. Python exposes a nice attribute- based interface as well
as a dictionary-like interface for getting (and, if appropriate, setting) these flags.
Memory areas of all kinds can be pointed to by an ndarray, necessitating these flags. If you get an arbitrary
PyArrayObject in C-code, you need to be aware of the flags that are set. If you need to guarantee a certain kind
of array (like NPY_CONTIGUOUS and NPY_BEHAVED), then pass these requirements into the PyArray_FromAny
function.
An ndarray can have a data segment that is not a simple contiguous chunk of well-behaved memory you can manip-
ulate. It may not be aligned with word boundaries (very important on some platforms). It might have its data in a
different byte-order than the machine recognizes. It might not be writeable. It might be in Fortan-contiguous order.
The array flags are used to indicate what can be said about data associated with an array.
NPY_C_CONTIGUOUS
The data area is in C-style contiguous order (last index varies the fastest).
NPY_F_CONTIGUOUS
The data area is in Fortran-style contiguous order (first index varies the fastest).
Notice that contiguous 1-d arrays are always both NPY_FORTRAN contiguous and C contiguous. Both of these flags
can be checked and are convenience flags only as whether or not an array is NPY_CONTIGUOUS or NPY_FORTRAN
can be determined by the strides, dimensions, and itemsize attributes.
NPY_OWNDATA
The data area is owned by this array.
NPY_ALIGNED
The data area is aligned appropriately (for all strides).
NPY_WRITEABLE
The data area can be written to.
Notice that the above 3 flags are are defined so that a new, well- behaved array has these flags defined as true.
NPY_UPDATEIFCOPY
The data area represents a (well-behaved) copy whose information should be transferred back to the original
when this array is deleted.
This is a special flag that is set if this array represents a copy made because a user required certain flags in
PyArray_FromAny and a copy had to be made of some other array (and the user asked for this flag to be
set in such a situation). The base attribute then points to the misbehaved array (which is set read_only).
When the array with this flag set is deallocated, it will copy its contents back to the misbehaved array
(casting if necessary) and will reset the misbehaved array to NPY_WRITEABLE. If the misbehaved ar-
ray was not NPY_WRITEABLE to begin with then PyArray_FromAny would have returned an error because
NPY_UPDATEIFCOPY would not have been possible.
PyArray_UpdateFlags (obj, flags) will update the obj->flags for flags which can be any of
NPY_CONTIGUOUS, NPY_FORTRAN, NPY_ALIGNED, or NPY_WRITEABLE.
NPY_BEHAVED
NPY_ALIGNED | NPY_WRITEABLE
NPY_CARRAY
NPY_C_CONTIGUOUS | NPY_BEHAVED
NPY_CARRAY_RO
NPY_C_CONTIGUOUS | NPY_ALIGNED
NPY_FARRAY
NPY_F_CONTIGUOUS | NPY_BEHAVED
NPY_FARRAY_RO
NPY_F_CONTIGUOUS | NPY_ALIGNED
NPY_DEFAULT
NPY_CARRAY
NPY_UPDATE_ALL
NPY_C_CONTIGUOUS | NPY_F_CONTIGUOUS | NPY_ALIGNED
Flag-like constants
These constants are used in PyArray_FromAny (and its macro forms) to specify desired properties of the new array.
NPY_FORCECAST
Cast to the desired type, even if it cant be done without losing information.
NPY_ENSURECOPY
Make sure the resulting array is a copy of the original.
NPY_ENSUREARRAY
Make sure the resulting object is an actual ndarray (or bigndarray), and not a sub-class.
NPY_NOTSWAPPED
Only used in PyArray_CheckFromAny to over-ride the byteorder of the data-type object passed in.
NPY_BEHAVED_NS
NPY_ALIGNED | NPY_WRITEABLE | NPY_NOTSWAPPED
Flag checking
For all of these macros arr must be an instance of a (subclass of) PyArray_Type, but no checking is done.
PyArray_CHKFLAGS(arr, flags)
The first parameter, arr, must be an ndarray or subclass. The parameter, flags, should be an integer consisting of
bitwise combinations of the possible flags an array can have: NPY_C_CONTIGUOUS, NPY_F_CONTIGUOUS,
NPY_OWNDATA, NPY_ALIGNED, NPY_WRITEABLE, NPY_UPDATEIFCOPY.
PyArray_ISCONTIGUOUS(arr)
Evaluates true if arr is C-style contiguous.
PyArray_ISFORTRAN(arr)
Evaluates true if arr is Fortran-style contiguous.
PyArray_ISWRITEABLE(arr)
Evaluates true if the data area of arr can be written to
PyArray_ISALIGNED(arr)
Evaluates true if the data area of arr is properly aligned on the machine.
PyArray_ISBEHAVED(arr)
Evalutes true if the data area of arr is aligned and writeable and in machine byte-order according to its descriptor.
PyArray_ISBEHAVED_RO(arr)
Evaluates true if the data area of arr is aligned and in machine byte-order.
PyArray_ISCARRAY(arr)
Evaluates true if the data area of arr is C-style contiguous, and PyArray_ISBEHAVED (arr) is true.
PyArray_ISFARRAY(arr)
Evaluates true if the data area of arr is Fortran-style contiguous and PyArray_ISBEHAVED (arr) is true.
PyArray_ISCARRAY_RO(arr)
Evaluates true if the data area of arr is C-style contiguous, aligned, and in machine byte-order.
PyArray_ISFARRAY_RO(arr)
Evaluates true if the data area of arr is Fortran-style contiguous, aligned, and in machine byte-order .
PyArray_ISONESEGMENT(arr)
Evaluates true if the data area of arr consists of a single (C-style or Fortran-style) contiguous segment.
void PyArray_UpdateFlags(PyArrayObject* arr, int flagmask)
The NPY_C_CONTIGUOUS, NPY_ALIGNED, and NPY_F_CONTIGUOUS array flags can be calculated
from the array object itself. This routine updates one or more of these flags of arr as specified in flagmask by
performing the required calculation.
Warning: It is important to keep the flags updated (using PyArray_UpdateFlags can help) whenever a
manipulation with an array is performed that might cause them to change. Later calculations in NumPy that rely
on the state of these flags do not repeat the calculation to update them.
Conversion
Shape Manipulation
Warning: matrix objects are always 2-dimensional. Therefore, PyArray_Squeeze has no effect on arrays of
matrix sub-class.
reversed. For example if self has shape 10 20 30, and permute .ptr is (0,2,1) the shape of the result is
10 30 20. If permute is NULL, the shape of the result is 30 20 10.
PyObject* PyArray_Flatten(PyArrayObject* self, NPY_ORDER order)
Equivalent to ndarray.flatten (self, order). Return a 1-d copy of the array. If order is
NPY_FORTRANORDER the elements are scanned out in Fortran order (first-dimension varies the fastest).
If order is NPY_CORDER, the elements of self are scanned in C-order (last dimension varies the fastest). If
order NPY_ANYORDER, then the result of PyArray_ISFORTRAN (self ) is used to determine which order to
flatten.
PyObject* PyArray_Ravel(PyArrayObject* self, NPY_ORDER order)
Equivalent to self.ravel(order). Same basic functionality as PyArray_Flatten (self, order) except if order
is 0 and self is C-style contiguous, the shape is altered but no copy is performed.
Calculation
Tip: Pass in NPY_MAXDIMS for axis in order to achieve the same effect that is obtained by passing in axis = None
in Python (treating the array as a 1-d array).
PyObject* PyArray_ArgMax(PyArrayObject* self, int axis)
Equivalent to ndarray.argmax (self, axis). Return the index of the largest element of self along axis.
PyObject* PyArray_ArgMin(PyArrayObject* self, int axis)
Equivalent to ndarray.argmin (self, axis). Return the index of the smallest element of self along axis.
PyObject* PyArray_Max(PyArrayObject* self, int axis, PyArrayObject* out)
Equivalent to ndarray.max (self, axis). Return the largest element of self along the given axis.
PyObject* PyArray_Min(PyArrayObject* self, int axis, PyArrayObject* out)
Equivalent to ndarray.min (self, axis). Return the smallest element of self along the given axis.
PyObject* PyArray_Ptp(PyArrayObject* self, int axis, PyArrayObject* out)
Equivalent to ndarray.ptp (self, axis). Return the difference between the largest element of self along axis
and the smallest element of self along axis.
Note: The rtype argument specifies the data-type the reduction should take place over. This is important if the data-
type of the array is not large enough to handle the output. By default, all integer data-types are made at least as large
as NPY_LONG for the add and multiply ufuncs (which form the basis for mean, sum, cumsum, prod, and cumprod
functions).
PyObject* PyArray_Mean(PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to ndarray.mean (self, axis, rtype). Returns the mean of the elements along the given axis,
using the enumerated type rtype as the data type to sum in. Default sum behavior is obtained using
PyArray_NOTYPE for rtype.
PyObject* PyArray_Trace(PyArrayObject* self, int offset, int axis1, int axis2, int rtype, PyArrayObject* out)
Equivalent to ndarray.trace (self, offset, axis1, axis2, rtype). Return the sum (using rtype as the data
type of summation) over the offset diagonal elements of the 2-d arrays defined by axis1 and axis2 variables. A
positive offset chooses diagonals above the main diagonal. A negative offset selects diagonals below the main
diagonal.
PyObject* PyArray_Clip(PyArrayObject* self, PyObject* min, PyObject* max)
Equivalent to ndarray.clip (self, min, max). Clip an array, self, so that values larger than max are fixed to
max and values less than min are fixed to min.
PyObject* PyArray_Conjugate(PyArrayObject* self )
Equivalent to ndarray.conjugate (self ). Return the complex conjugate of self. If self is not of complex
data type, then return self with an reference.
PyObject* PyArray_Round(PyArrayObject* self, int decimals, PyArrayObject* out)
Equivalent to ndarray.round (self, decimals, out). Returns the array with elements rounded to the nearest
decimal place. The decimal place is defined as the 10decimals digit so that negative decimals cause rounding to
the nearest 10s, 100s, etc. If out is NULL, then the output array is created, otherwise the output is placed in out
which must be the correct size and type.
PyObject* PyArray_Std(PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to ndarray.std (self, axis, rtype). Return the standard deviation using data along axis converted
to data type rtype.
PyObject* PyArray_Sum(PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to ndarray.sum (self, axis, rtype). Return 1-d vector sums of elements in self along axis. Perform
the sum after converting data to data type rtype.
PyObject* PyArray_CumSum(PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to ndarray.cumsum (self, axis, rtype). Return cumulative 1-d sums of elements in self along
axis. Perform the sum after converting data to data type rtype.
PyObject* PyArray_Prod(PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to ndarray.prod (self, axis, rtype). Return 1-d products of elements in self along axis. Perform
the product after converting data to data type rtype.
PyObject* PyArray_CumProd(PyArrayObject* self, int axis, int rtype, PyArrayObject* out)
Equivalent to ndarray.cumprod (self, axis, rtype). Return 1-d cumulative products of elements in self
along axis. Perform the product after converting data to data type rtype.
PyObject* PyArray_All(PyArrayObject* self, int axis, PyArrayObject* out)
Equivalent to ndarray.all (self, axis). Return an array with True elements for every 1-d sub-array of self
defined by axis in which all the elements are True.
PyObject* PyArray_Any(PyArrayObject* self, int axis, PyArrayObject* out)
Equivalent to ndarray.any (self, axis). Return an array with True elements for every 1-d sub-array of self
defined by axis in which any of the elements are True.
5.4.6 Functions
Array Functions
int PyArray_AsCArray(PyObject** op, void* ptr, npy_intp* dims, int nd, int typenum, int itemsize)
Sometimes it is useful to access a multidimensional array as a C-style multi-dimensional array so that algorithms
can be implemented using Cs a[i][j][k] syntax. This routine returns a pointer, ptr, that simulates this kind of
C-style array, for 1-, 2-, and 3-d ndarrays.
Parameters
op The address to any Python object. This Python object will be replaced with an equiv-
alent well-behaved, C-style contiguous, ndarray of the given data type specifice by the last
two arguments. Be sure that stealing a reference in this way to the input object is justified.
ptr The address to a (ctype* for 1-d, ctype** for 2-d or ctype*** for 3-d) variable where
ctype is the equivalent C-type for the data type. On return, ptr will be addressable as a 1-d,
2-d, or 3-d array.
dims An output array that contains the shape of the array object. This array gives bound-
aries on any looping that will take place.
nd The dimensionality of the array (1, 2, or 3).
typenum The expected data type of the array.
itemsize This argument is only needed when typenum represents a flexible array. Otherwise
it should be 0.
Note: The simulation of a C-style array is not complete for 2-d and 3-d arrays. For example, the simulated arrays of
pointers cannot be passed to subroutines expecting specific, statically-defined 2-d and 3-d arrays. To pass to functions
requiring those kind of inputs, you must statically define the required array and copy data.
int PyArray_Free(PyObject* op, void* ptr)
Must be called with the same objects and memory locations returned from PyArray_AsCArray (...). This
function cleans up memory that otherwise would get leaked.
PyObject* PyArray_Concatenate(PyObject* obj, int axis)
Join the sequence of objects in obj together along axis into a single array. If the dimensions or types are not
compatible an error is raised.
PyObject* PyArray_InnerProduct(PyObject* obj1, PyObject* obj2)
Compute a product-sum over the last dimensions of obj1 and obj2. Neither array is conjugated.
PyObject* PyArray_MatrixProduct(PyObject* obj1, PyObject* obj)
Compute a product-sum over the last dimension of obj1 and the second-to-last dimension of obj2. For 2-d
arrays this is a matrix-product. Neither array is conjugated.
PyObject* PyArray_CopyAndTranspose(PyObject * op)
A specialized copy and transpose function that works only for 2-d arrays. The returned array is a transposed
copy of op.
PyObject* PyArray_Correlate(PyObject* op1, PyObject* op2, int mode)
Compute the 1-d correlation of the 1-d arrays op1 and op2 . The correlation is computed at each output point
by multiplying op1 by a shifted version of op2 and summing the result. As a result of the shift, needed values
outside of the defined range of op1 and op2 are interpreted as zero. The mode determines how many shifts to
return: 0 - return only shifts that did not need to assume zero- values; 1 - return an object that is the same size
as op1, 2 - return all possible shifts (any overlap at all is accepted).
Notes
This does not compute the usual correlation: if op2 is larger than op1, the arguments are swapped, and the
conjugate is never taken for complex arrays. See PyArray_Correlate2 for the usual signal processing correlation.
PyObject* PyArray_Correlate2(PyObject* op1, PyObject* op2, int mode)
Updated version of PyArray_Correlate, which uses the usual definition of correlation for 1d arrays. The corre-
lation is computed at each output point by multiplying op1 by a shifted version of op2 and summing the result.
As a result of the shift, needed values outside of the defined range of op1 and op2 are interpreted as zero. The
mode determines how many shifts to return: 0 - return only shifts that did not need to assume zero- values; 1 -
return an object that is the same size as op1, 2 - return all possible shifts (any overlap at all is accepted).
Notes
Compute z as follows:
Other functions
Bool PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp* dims, npy_intp* newstrides)
Determine if newstrides is a strides array consistent with the memory of an nd -dimensional array with shape
dims and element-size, elsize. The newstrides array is checked to see if jumping by the provided number of
bytes in each direction will ever mean jumping more than numbytes which is the assumed size of the available
memory segment. If numbytes is 0, then an equivalent numbytes is computed assuming nd, dims, and elsize
refer to a single-segment array. Return NPY_TRUE if newstrides is acceptable, otherwise return NPY_FALSE.
npy_intp PyArray_MultiplyList(npy_intp* seq, int n)
An array iterator is a simple way to access the elements of an N-dimensional array quickly and efficiently. Section 2
provides more description and examples of this useful approach to looping over an array.
PyObject* PyArray_IterNew(PyObject* arr)
Return an array iterator object from the array, arr. This is equivalent to arr. flat. The array iterator object
makes it easy to loop over an N-dimensional non-contiguous array in C-style contiguous fashion.
PyObject* PyArray_IterAllButAxis(PyObject* arr, int *axis)
Return an array iterator that will iterate over all axes but the one provided in *axis. The returned iterator cannot
be used with PyArray_ITER_GOTO1D. This iterator could be used to write something similar to what ufuncs
do wherein the loop over the largest axis is done by a separate sub-routine. If *axis is negative then *axis will
be set to the axis having the smallest stride and that axis will be used.
New in version 1.4.0. Neighborhood iterators are subclasses of the iterator object, and can be used to iter over a
neighborhood of a point. For example, you may want to iterate over every voxel of a 3d image, and for every such
voxel, iterate over an hypercube. Neighborhood iterator automatically handle boundaries, thus making this kind of
code much easier to write than manual boundaries handling, at the cost of a slight overhead.
PyObject* PyArray_NeighborhoodIterNew(PyArrayIterObject* iter, npy_intp bounds, int mode,
PyArrayObject* fill_value)
This function creates a new neighborhood iterator from an existing iterator. The neighborhood will be computed
relatively to the position currently pointed by iter, the bounds define the shape of the neighborhood iterator, and
the mode argument the boundaries handling mode.
The bounds argument is expected to be a (2 * iter->ao->nd) arrays, such as the range bound[2*i]->bounds[2*i+1]
defines the range where to walk for dimension i (both bounds are included in the walked coordinates). The
bounds should be ordered for each dimension (bounds[2*i] <= bounds[2*i+1]).
The mode should be one of:
NPY_NEIGHBORHOOD_ITER_ZERO_PADDING: zero padding. Outside bounds values will be 0.
NPY_NEIGHBORHOOD_ITER_ONE_PADDING: one padding, Outside bounds values will be 1.
NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING: constant padding. Outside bounds values
will be the same as the first item in fill_value.
NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING: mirror padding. Outside bounds values will be
as if the array items were mirrored. For example, for the array [1, 2, 3, 4], x[-2] will be 2, x[-2] will be 1,
x[4] will be 4, x[5] will be 1, etc...
NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING: circular padding. Outside bounds values will
be as if the array was repeated. For example, for the array [1, 2, 3, 4], x[-2] will be 3, x[-2] will be 4, x[4]
will be 1, x[5] will be 2, etc...
If the mode is constant filling (NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING), fill_value should
point to an array object which holds the filling value (the first item will be the filling value if the array contains
more than one item). For other cases, fill_value may be NULL.
The iterator holds a reference to iter
Return NULL on failure (in which case the reference count of iter is not changed)
iter itself can be a Neighborhood iterator: this can be useful for .e.g automatic boundaries handling
the object returned by this function should be safe to use as a normal iterator
PyArrayIterObject \*iter;
PyArrayNeighborhoodIterObject \*neigh_iter;
iter = PyArray_IterNew(x);
Warning: Data-type objects must be reference counted so be aware of the action on the data-type reference
of different C-API calls. The standard rule is that when a data-type object is returned it is a new reference.
Functions that take PyArray_Descr * objects and return arrays steal references to the data-type their inputs
unless otherwise noted. Therefore, you must own a reference to any data-type object used as input to such a
function.
confuse this function with PyArray_DescrConverter. This function essentially looks at all the objects in
the (nested) sequence and determines the data-type from the elements it finds.
PyArray_Descr* PyArray_DescrFromScalar(PyObject* scalar)
Return a data-type object from an array-scalar object. No checking is done to be sure that scalar is an array
scalar. If no suitable data-type can be determined, then a data-type of NPY_OBJECT is returned by default.
PyArray_Descr* PyArray_DescrFromType(int typenum)
Returns a data-type object corresponding to typenum. The typenum can be one of the enumerated types, a
character code for one of the enumerated types, or a user-defined type.
int PyArray_DescrConverter(PyObject* obj, PyArray_Descr** dtype)
Convert any compatible Python object, obj, to a data-type object in dtype. A large number of Python objects
can be converted to data-type objects. See Data type objects (dtype) for a complete description. This version of
the converter converts None objects to a NPY_DEFAULT_TYPE data-type object. This function can be used
with the O& character code in PyArg_ParseTuple processing.
int PyArray_DescrConverter2(PyObject* obj, PyArray_Descr** dtype)
Convert any compatible Python object, obj, to a data-type object in dtype. This version of the converter converts
None objects so that the returned data-type is NULL. This function can also be used with the O& character in
PyArg_ParseTuple processing.
int Pyarray_DescrAlignConverter(PyObject* obj, PyArray_Descr** dtype)
Like PyArray_DescrConverter except it aligns C-struct-like objects on word-boundaries as the compiler
would.
int Pyarray_DescrAlignConverter2(PyObject* obj, PyArray_Descr** dtype)
Like PyArray_DescrConverter2 except it aligns C-struct-like objects on word-boundaries as the com-
piler would.
PyObject * PyArray_FieldNames(PyObject* dict)
Take the fields dictionary, dict, such as the one attached to a data-type object and construct an ordered-list of
field names such as is stored in the names field of the PyArray_Descr object.
All of these functions can be used in PyArg_ParseTuple (...) with the O& format specifier to automatically
convert any Python object to the required C-object. All of these functions return NPY_SUCCEED if successful and
NPY_FAIL if not. The first argument to all of these function is a Python object. The second argument is the address
of the C-type to convert the Python object to.
Warning: Be sure to understand what steps you should take to manage the memory when using these conversion
functions. These functions can require freeing memory, and/or altering the reference counts of specific objects
based on your use.
be NULL but the call will succeed. If PyArray_Check ( obj) is TRUE then it is returned in *address without
incrementing its reference count.
int PyArray_IntpConverter(PyObject* obj, PyArray_Dims* seq)
Convert any Python sequence, obj, smaller than NPY_MAXDIMS to a C-array of npy_intp. The Python
object could also be a single number. The seq variable is a pointer to a structure with members ptr and len.
On successful return, seq ->ptr contains a pointer to memory that must be freed to avoid a memory leak.
The restriction on memory size allows this converter to be conveniently used for sequences intended to be
interpreted as array shapes.
int PyArray_BufferConverter(PyObject* obj, PyArray_Chunk* buf )
Convert any Python object, obj, with a (single-segment) buffer interface to a variable with members that detail
the objects use of its chunk of memory. The buf variable is a pointer to a structure with base, ptr, len, and flags
members. The PyArray_Chunk structure is binary compatibile with the Pythons buffer object (through its
len member on 32-bit platforms and its ptr member on 64-bit platforms or in Python 2.5). On return, the base
member is set to obj (or its base if obj is already a buffer object pointing to another object). If you need to
hold on to the memory be sure to INCREF the base member. The chunk of memory is pointed to by buf ->ptr
member and has length buf ->len. The flags member of buf is NPY_BEHAVED_RO with the NPY_WRITEABLE
flag set if obj has a writeable buffer interface.
int PyArray_AxisConverter(PyObject * obj, int* axis)
Convert a Python object, obj, representing an axis argument to the proper value for passing to the functions that
take an integer axis. Specifically, if obj is None, axis is set to NPY_MAXDIMS which is interpreted correctly by
the C-API functions that take axis arguments.
int PyArray_BoolConverter(PyObject* obj, Bool* value)
Convert any Python object, obj, to NPY_TRUE or NPY_FALSE, and place the result in value.
int PyArray_ByteorderConverter(PyObject* obj, char* endian)
Convert Python strings into the corresponding byte-order character: >, <, s, =, or |.
int PyArray_SortkindConverter(PyObject* obj, NPY_SORTKIND* sort)
Convert Python strings into one of NPY_QUICKSORT (starts with q or Q) , NPY_HEAPSORT (starts with
h or H), or NPY_MERGESORT (starts with m or M).
int PyArray_SearchsideConverter(PyObject* obj, NPY_SEARCHSIDE* side)
Convert Python strings into one of NPY_SEARCHLEFT (starts with l or L), or NPY_SEARCHRIGHT (starts
with r or R).
Other conversions
5.4.13 Miscellaneous
In order to make use of the C-API from another extension module, the import_array () command must be used.
If the extension module is self-contained in a single .c file, then that is all that needs to be done. If, however, the
extension module involves multiple files where the C-API is needed then some additional steps must be taken.
void import_array(void)
This function must be called in the initialization section of a module that will make use of the C-API. It imports
the module where the function-pointer table is stored and points the correct variable to it.
PY_ARRAY_UNIQUE_SYMBOL
NO_IMPORT_ARRAY
Using these #defines you can use the C-API in multiple files for a single extension module. In each file you
must define PY_ARRAY_UNIQUE_SYMBOL to some name that will hold the C-API (e.g. myexten-
sion_ARRAY_API). This must be done before including the numpy/arrayobject.h file. In the module
intialization routine you call import_array (). In addition, in the files that do not have the module
initialization sub_routine define NO_IMPORT_ARRAY prior to including numpy/arrayobject.h.
Suppose I have two files coolmodule.c and coolhelper.c which need to be compiled and linked into a single
extension module. Suppose coolmodule.c contains the required initcool module initialization function (with the
import_array() function called). Then, coolmodule.c would have at the top:
Because python extensions are not used in the same way as usual libraries on most platforms, some errors cannot
be automatically detected at build time or even runtime. For example, if you build an extension using a function
available only for numpy >= 1.3.0, and you import the extension later with numpy 1.2, you will not get an import error
(but almost certainly a segmentation fault when calling the function). Thats why several functions are provided to
check for numpy versions. The macros NPY_VERSION and NPY_FEATURE_VERSION corresponds to the numpy
version used to build the extension, whereas the versions returned by the functions PyArray_GetNDArrayCVersion
and PyArray_GetNDArrayCFeatureVersion corresponds to the runtime numpys version.
The rules for ABI and API compatibilities can be summarized as follows:
Whenever NPY_VERSION != PyArray_GetNDArrayCVersion, the extension has to be recompiled (ABI incom-
patibility).
Internal Flexibility
Memory management
PyDataMem_FREE(char* ptr)
PyDimMem_FREE(npy_intp* ptr)
PyArray_free(ptr)
PyArray_realloc(ptr, nbytes)
These macros use different memory allocators, depending on the constant NPY_USE_PYMEM. The system
malloc is used when NPY_USE_PYMEM is 0, if NPY_USE_PYMEM is 1, then the Python memory allocator is
used.
Threading support
These macros are only meaningful if NPY_ALLOW_THREADS evaluates True during compilation of the extension
module. Otherwise, these macros are equivalent to whitespace. Python uses a single Global Interpreter Lock (GIL)
for each Python process so that only a single thread may excecute at a time (even on multi-cpu machines). When
calling out to a compiled function that may take time to compute (and does not have side-effects for other threads like
updated global variables), the GIL should be released so that other Python threads can run while the time-consuming
calculations are performed. This can be accomplished using two groups of macros. Typically, if one macro in a group
is used in a code block, all of them must be used in the same code block. Currently, NPY_ALLOW_THREADS is
defined to the python-defined WITH_THREADS constant unless the environment variable NPY_NOSMP is set in which
case NPY_ALLOW_THREADS is defined to be 0.
Group 1
This group is used to call code that may take some time but does not use any Python C-API calls. Thus,
the GIL should be released during its calculation.
NPY_BEGIN_ALLOW_THREADS
Equivalent to Py_BEGIN_ALLOW_THREADS except it uses NPY_ALLOW_THREADS to determine
if the macro if replaced with white-space or not.
NPY_END_ALLOW_THREADS
Equivalent to Py_END_ALLOW_THREADS except it uses NPY_ALLOW_THREADS to determine if
the macro if replaced with white-space or not.
NPY_BEGIN_THREADS_DEF
Place in the variable declaration area. This macro sets up the variable needed for storing the Python
state.
NPY_BEGIN_THREADS
Place right before code that does not need the Python interpreter (no Python C-API calls). This
macro saves the Python state and releases the GIL.
NPY_END_THREADS
Place right after code that does not need the Python interpreter. This macro acquires the GIL and
restores the Python state from the saved variable.
NPY_BEGIN_THREADS_DESCR(PyArray_Descr *dtype)
Useful to release the GIL only if dtype does not contain arbitrary Python objects which may need
the Python interpreter during execution of the loop. Equivalent to
NPY_END_THREADS_DESCR(PyArray_Descr *dtype)
Useful to regain the GIL in situations where it was released using the BEGIN form of this macro.
Group 2
This group is used to re-acquire the Python GIL after it has been released. For example, suppose the
GIL has been released (using the previous calls), and then some path in the code (perhaps in a different
subroutine) requires use of the Python C-API, then these macros are useful to acquire the GIL. These
macros accomplish essentially a reverse of the previous three (acquire the LOCK saving what state it had)
and then re-release it with the saved state.
NPY_ALLOW_C_API_DEF
Place in the variable declaration area to set up the necessary variable.
NPY_ALLOW_C_API
Place before code that needs to call the Python C-API (when it is known that the GIL has already
been released).
NPY_DISABLE_C_API
Place after code that needs to call the Python C-API (to re-release the GIL).
Tip: Never use semicolons after the threading support macros.
Priority
NPY_PRIOIRTY
Default priority for arrays.
NPY_SUBTYPE_PRIORITY
Default subtype priority.
NPY_SCALAR_PRIORITY
Default scalar priority (very small)
double PyArray_GetPriority(PyObject* obj, double def )
Return the __array_priority__ attribute (converted to a double) of obj or def if no attribute of that name
exists. Fast returns that avoid the attribute lookup are provided for objects of type PyArray_Type.
Default buffers
NPY_BUFSIZE
Default size of the user-settable internal buffers.
NPY_MIN_BUFSIZE
Smallest size of user-settable internal buffers.
NPY_MAX_BUFSIZE
Largest size allowed for the user-settable buffers.
Other constants
NPY_NUM_FLOATTYPE
The number of floating-point types
NPY_MAXDIMS
The maximum number of dimensions allowed in arrays.
NPY_VERSION
The current version of the ndarray object (check to see if this variable is defined to guarantee the
numpy/arrayobject.h header is being used).
NPY_FALSE
Defined as 0 for use with Bool.
NPY_TRUE
Defined as 1 for use with Bool.
NPY_FAIL
The return value of failed converter functions which are called using the O& syntax in
PyArg_ParseTuple-like functions.
NPY_SUCCEED
The return value of successful converter functions which are called using the O& syntax in
PyArg_ParseTuple-like functions.
Miscellaneous Macros
PyArray_SAMESHAPE(a1, a2)
Evaluates as True if arrays a1 and a2 have the same shape.
PyArray_MAX(a, b)
Returns the maximum of a and b. If (a) or (b) are expressions they are evaluated twice.
PyArray_MIN(a, b)
Returns the minimum of a and b. If (a) or (b) are expressions they are evaluated twice.
PyArray_CLT(a, b)
PyArray_CGT(a, b)
PyArray_CLE(a, b)
PyArray_CGE(a, b)
PyArray_CEQ(a, b)
PyArray_CNE(a, b)
Implements the complex comparisons between two complex numbers (structures with a real and imag member)
using NumPys definition of the ordering which is lexicographic: comparing the real parts first and then the
complex parts if the real parts are equal.
PyArray_REFCOUNT(PyObject* op)
Returns the reference count of any Python object.
PyArray_XDECREF_ERR(PyObject *obj)
DECREFs an array object which may have the NPY_UPDATEIFCOPY flag set without causing the contents to
be copied back into the original array. Resets the NPY_WRITEABLE flag on the base object. This is useful for
recovering from an error condition when NPY_UPDATEIFCOPY is used.
Enumerated Types
NPY_SORTKIND
A special variable-type which can take on the values NPY_{KIND} where {KIND} is
QUICKSORT, HEAPSORT, MERGESORT
NPY_NSORTS
Defined to be the number of sorts.
NPY_SCALARKIND
A special variable type indicating the number of kinds of scalars distinguished in determining scalar-coercion
rules. This variable can take on the values NPY_{KIND} where {KIND} can be
NOSCALAR, BOOL_SCALAR, INTPOS_SCALAR, INTNEG_SCALAR, FLOAT_SCALAR,
COMPLEX_SCALAR, OBJECT_SCALAR
NPY_NSCALARKINDS
Defined to be the number of scalar kinds (not including NPY_NOSCALAR).
NPY_ORDER
A variable type indicating the order that an array should be interpreted in. The value of a variable of this type
can be NPY_{ORDER} where {ORDER} is
ANYORDER, CORDER, FORTRANORDER
NPY_CLIPMODE
A variable type indicating the kind of clipping that should be applied in certain functions. The value of a
variable of this type can be NPY_{MODE} where {MODE} is
CLIP, WRAP, RAISE
5.5.1 Constants
UFUNC_ERR_{HANDLER}
{HANDLER} can be IGNORE, WARN, RAISE, or CALL
UFUNC_{THING}_{ERR}
{THING} can be MASK, SHIFT, or FPE, and {ERR} can be DIVIDEBYZERO, OVERFLOW, UNDER-
FLOW, and INVALID.
PyUFunc_{VALUE}
{VALUE} can be One (1), Zero (0), or None (-1)
5.5.2 Macros
NPY_LOOP_BEGIN_THREADS
Used in universal function code to only release the Python GIL if loop->obj is not true (i.e. this is not an
OBJECT array loop). Requires use of NPY_BEGIN_THREADS_DEF in variable declaration area.
NPY_LOOP_END_THREADS
Used in universal function code to re-acquire the Python GIL if it was released (because loop->obj was not
true).
UFUNC_CHECK_ERROR(loop)
A macro used internally to check for errors and goto fail if found. This macro requires a fail label in the current
code block. The loop variable must have at least members (obj, errormask, and errorobj). If loop ->obj is
nonzero, then PyErr_Occurred () is called (meaning the GIL must be held). If loop ->obj is zero, then if
loop ->errormask is nonzero, PyUFunc_checkfperr is called with arguments loop ->errormask and loop
->errobj. If the result of this check of the IEEE floating point registers is true then the code redirects to the fail
label which must be defined.
UFUNC_CHECK_STATUS(ret)
A macro that expands to platform-dependent code. The ret variable can can be any integer. The
UFUNC_FPE_{ERR} bits are set in ret according to the status of the corresponding error flags of the
floating point processor.
5.5.3 Functions
void** data, char* types, int ntypes, int nin, int nout, int identity,()
Create a new broadcasting universal function from required variables. Each ufunc builds around
the notion of an element-by-element operation. Each ufunc object contains pointers to 1-d loops
implementing the basic functionality for each supported type.
Note: The func, data, types, name, and doc arguments are not copied by
PyUFunc_FromFuncAndData. The caller must ensure that the memory used by these
arrays is not freed as long as the ufunc object is alive.
param func
Must to an array of length ntypes containing PyUFuncGenericFunction items.
These items are pointers to functions that actually implement the underlying (element-
by-element) function N times.
param data
Should be NULL or a pointer to an array of size ntypes . This array may contain arbitrary
extra-data to be passed to the corresponding 1-d loop function in the func array.
param types
Must be of length (nin + nout) * ntypes, and it contains the data-types (built-in only)
that the corresponding function in the func array can deal with.
param ntypes
How many different data-type signatures the ufunc has implemented.
param nin
The number of inputs to this operation.
param nout
The number of outputs
param name
The name for the ufunc. Specifying a name of add or multiply enables a special
behavior for integer-typed reductions when no dtype is given. If the input type is an
integer (or boolean) data type smaller than the size of the int_ data type, it will be
internally upcast to the int_ (or uint) data type.
param doc
Allows passing in a documentation string to be stored with the ufunc. The documen-
tation string should not contain the name of the function or the calling signature as
that will be dynamically determined from the object and available when accessing the
__doc__ attribute of the ufunc.
param check_return
Unused and present for backwards compatibility of the C-API. A corresponding
check_return integer does exist in the ufunc structure and it does get set with this value
when the ufunc object is created.
int PyUFunc_RegisterLoopForType(PyUFuncObject* ufunc,()
This function allows the user to register a 1-d loop with an already- created ufunc to be used whenever
the ufunc is called with any of its input arguments as the user-defined data-type. This is needed
in order to make ufuncs work with built-in data-types. The data-type must have been previously
registered with the numpy system. The loop is passed in as function. This loop can take arbitrary
data which should be passed in as data. The data-types the loop requires are passed in as arg_types
which must be a pointer to memory at least as large as ufunc->nargs.
int PyUFunc_ReplaceLoopBySignature(PyUFuncObject* ufunc,()
PyUFuncGenericFunction* oldfunc)()
Replace a 1-d loop matching the given signature in the already-created ufunc with the new 1-d loop
newfunc. Return the old 1-d loop function in oldfunc. Return 0 on success and -1 on failure. This
function works only with built-in types (use PyUFunc_RegisterLoopForType for user-defined
types). A signature is an array of data-type numbers indicating the inputs followed by the outputs
assumed by the 1-d loop.
int PyUFunc_GenericFunction(PyUFuncObject* self,()
A generic ufunc call. The ufunc is passed in as self, the arguments to the ufunc as args. The mps
argument is an array of PyArrayObject pointers containing the converted input arguments as
well as the ufunc outputs on return. The user is responsible for managing this array and receives a
new reference for each array in mps. The total number of arrays in mps is given by self ->nin + self
->nout.
int PyUFunc_checkfperr(int errmask, PyObject* errobj)
A simple interface to the IEEE error-flag checking support. The errmask argument is a mask of
UFUNC_MASK_{ERR} bitmasks indicating which errors to check for (and how to check for them). The
errobj must be a Python tuple with two elements: a string containing the name which will be used in any
communication of error and either a callable Python object (call-back function) or Py_None. The callable
object will only be used if UFUNC_ERR_CALL is set as the desired error checking method. This routine
manages the GIL and is safe to call even after releasing the GIL. If an error in the IEEE-compatibile hardware
is determined a -1 is returned, otherwise a 0 is returned.
void PyUFunc_clearfperr()
Clear the IEEE error flags.
Get the Python values used for ufunc processing from the thread-local storage area unless the defaults
have been set in which case the name lookup is bypassed. The name is placed as a string in the first
element of *errobj. The second element is the looked-up function to call on error callback. The value
of the looked-up buffer-size to use is passed into bufsize, and the value of the error mask is placed
into errmask.
At the core of every ufunc is a collection of type-specific functions that defines the basic functionality for each of the
supported types. These functions must evaluate the underlying function N 1 times. Extra-data may be passed in
that may be used during the calculation. This feature allows some general functions to be used as these basic looping
functions. The general function has all the code needed to point variables to the right place and set up a function call.
The general function assumes that the actual function to call is passed in as the extra data and calls it with the correct
values. All of these functions are suitable for placing directly in the array of functions stored in the functions member
of the PyUFuncObject structure.
void PyUFunc_f_f_As_d_d(char** args, npy_intp* dimensions,()
Type specific, core 1-d functions for ufuncs where each calculation is obtained by calling a function
taking one input argument and returning one output. This function is passed in func. The letters
correspond to dtypechars of the supported data types ( f - float, d - double, g - long double, F - cfloat,
D - cdouble, G - clongdouble). The argument func must support the same signature. The _As_X_X
variants assume ndarrays of one data type but cast the values to use an underlying function that takes
a different data type. Thus, PyUFunc_f_f_As_d_d uses ndarrays of data type NPY_FLOAT but
calls out to a C-function that takes double and returns double.
void PyUFunc_ff_f_As_dd_d(char** args, npy_intp* dimensions,()
Type specific, core 1-d functions for ufuncs where each calculation is obtained by calling a function
taking two input arguments and returning one output. The underlying function to call is passed in as
func. The letters correspond to dtypechars of the specific data type supported by the general-purpose
function. The argument func must support the corresponding signature. The _As_XX_X variants
assume ndarrays of one data type but cast the values at each iteration of the loop to use the underlying
function that takes a different data type.
One-input, one-output, and two-input, one-output core 1-d functions for the NPY_OBJECT data
type. These functions handle reference count issues and return early on error. The actual func-
tion to call is func and it must accept calls with the signature (PyObject*) (PyObject*) for
PyUFunc_O_O or (PyObject*)(PyObject *, PyObject *) for PyUFunc_OO_O.
void PyUFunc_O_O_method(char** args, npy_intp* dimensions,()
This general purpose 1-d core function assumes that func is a string representing a method of the
input object. For each iteration of the loop, the Python obejct is extracted from the array and its func
method is called returning the result to the output array.
void PyUFunc_OO_O_method(char** args, npy_intp* dimensions,()
This general purpose 1-d core function assumes that func is a string representing a method of the input
object that takes one argument. The first argument in args is the method whose function is called, the
second argument in args is the argument passed to the function. The output of the function is stored
in the third entry of args.
void PyUFunc_On_Om(char** args, npy_intp* dimensions,()
This is the 1-d core function used by the dynamic ufuncs created by umath.frompyfunc(function, nin,
nout). In this case func is a pointer to a PyUFunc_PyFuncData structure which has definition
PyUFunc_PyFuncData
typedef struct {
int nin;
int nout;
PyObject *callable;
} PyUFunc_PyFuncData;
At each iteration of the loop, the nin input objects are exctracted from their object arrays and placed
into an argument tuple, the Python callable is called with the input arguments, and the nout outputs
are placed into their object arrays.
PY_UFUNC_UNIQUE_SYMBOL
NO_IMPORT_UFUNC
void import_ufunc(void)
These are the constants and functions for accessing the ufunc C-API from extension modules in precisely
the same way as the array C-API can be accessed. The import_ufunc () function must always be called
(in the initialization subroutine of the extension module). If your extension module is in one file then that is
all that is required. The other two constants are useful if your extension module makes use of multiple files.
In that case, define PY_UFUNC_UNIQUE_SYMBOL to something unique to your code and then in source
files that do not contain the module initialization function but still need access to the UFUNC API, define
PY_UFUNC_UNIQUE_SYMBOL to the same name used previously and also define NO_IMPORT_UFUNC.
The C-API is actually an array of function pointers. This array is created (and pointed to by a global variable)
by import_ufunc. The global variable is either statically defined or allowed to be seen by other files depending
on the state of Py_UFUNC_UNIQUE_SYMBOL and NO_IMPORT_UFUNC.
There is a general need for looping over not only functions on scalars but also over functions on vectors (or arrays),
as explained on http://scipy.org/scipy/numpy/wiki/GeneralLoopingFunctions. We propose to realize this concept by
generalizing the universal functions (ufuncs), and provide a C implementation that adds ~500 lines to the numpy code
base. In current (specialized) ufuncs, the elementary function is limited to element-by-element operations, whereas the
generalized version supports sub-array by sub-array operations. The Perl vector library PDL provides a similar
functionality and its terms are re-used in the following.
Each generalized ufunc has information associated with it that states what the core dimensionality of the inputs is,
as well as the corresponding dimensionality of the outputs (the element-wise ufuncs have zero core dimensions). The
list of the core dimensions for all arguments is called the signature of a ufunc. For example, the ufunc numpy.add
has signature (),()->() defining two scalar inputs and one scalar output.
Another example is (see the GeneralLoopingFunctions page) the function inner1d(a,b) with a signature of
(i),(i)->(). This applies the inner product along the last axis of each input, but keeps the remaining indices
intact. For example, where a is of shape (3,5,N) and b is of shape (5,N), this will return an output of shape
(3,5). The underlying elementary function is called 3*5 times. In the signature, we specify one core dimension (i)
for each input and zero core dimensions () for the output, since it takes two 1-d arrays and returns a scalar. By using
the same name i, we specify that the two corresponding dimensions should be of the same size (or one of them is of
size 1 and will be broadcasted).
The dimensions beyond the core dimensions are called loop dimensions. In the above example, this corresponds to
(3,5).
The usual numpy broadcasting rules apply, where the signature determines how the dimensions of each input/output
object are split into core and loop dimensions:
1. While an input array has a smaller dimensionality than the corresponding number of core dimensions, 1s are
pre-pended to its shape.
2. The core dimensions are removed from all inputs and the remaining dimensions are broadcasted; defining the
loop dimensions.
3. The output is given by the loop dimensions plus the output core dimensions.
5.6.1 Definitions
Elementary Function
Each ufunc consists of an elementary function that performs the most basic operation on the smallest portion of
array arguments (e.g. adding two numbers is the most basic operation in adding two arrays). The ufunc applies
the elementary function multiple times on different parts of the arrays. The input/output of elementary functions
can be vectors; e.g., the elementary function of inner1d takes two vectors as input.
Signature
A signature is a string describing the input/output dimensions of the elementary function of a ufunc. See section
below for more details.
Core Dimension
The dimensionality of each input/output of an elementary function is defined by its core dimensions (zero core
dimensions correspond to a scalar input/output). The core dimensions are mapped to the last dimensions of the
input/output arrays.
Dimension Name
A dimension name represents a core dimension in the signature. Different dimensions may share a name,
indicating that they are of the same size (or are broadcastable).
Dimension Index
A dimension index is an integer representing a dimension name. It enumerates the dimension names according
to the order of the first occurrence of each name in the signature.
The signature defines core dimensionality of input and output variables, and thereby also defines the contraction of
the dimensions. The signature is represented by a string of the following format:
Core dimensions of each input or output array are represented by a list of dimension names in parentheses,
(i_1,...,i_N); a scalar input/output is denoted by (). Instead of i_1, i_2, etc, one can use any valid
Python variable name.
Dimension lists for different arguments are separated by ",". Input/output arguments are separated by "->".
If one uses the same dimension name in multiple locations, this enforces the same size (or broadcastable size)
of the corresponding dimensions.
The formal syntax of signatures is as follows:
Notes:
1. All quotes are for clarity.
2. Core dimensions that share the same name must be broadcastable, as the two i in our example above. Each
dimension name typically corresponding to one level of looping in the elementary functions implementation.
3. White spaces are ignored.
The current interface remains unchanged, and PyUFunc_FromFuncAndData can still be used to implement (spe-
cialized) ufuncs, consisting of scalar elementary functions.
One can use PyUFunc_FromFuncAndDataAndSignature to declare a more general ufunc. The argument list
is the same as PyUFunc_FromFuncAndData, with an additional argument specifying the signature as C string.
Furthermore, the callback function is of the same type as before, void (*foo)(char **args, intp
*dimensions, intp *steps, void *func). When invoked, args is a list of length nargs containing
the data of all input/output arguments. For a scalar elementary function, steps is also of length nargs, denoting the
strides used for the arguments. dimensions is a pointer to a single integer defining the size of the axis to be looped
over.
For a non-trivial signature, dimensions will also contain the sizes of the core dimensions as well, starting at the
second entry. Only one size is provided for each unique dimension name and the sizes are given according to the first
occurrence of a dimension name in the signature.
The first nargs elements of steps remain the same as for scalar ufuncs. The following elements contain the strides
of all core dimensions for all arguments in order.
For example, consider a ufunc with signature (i,j),(i)->(). In this case, args will contain three pointers to the
data of the input/output arrays a, b, c. Furthermore, dimensions will be [N, I, J] to define the size of N of
the loop and the sizes I and J for the core dimensions i and j. Finally, steps will be [a_N, b_N, c_N, a_i,
a_j, b_i], containing all necessary strides.
New in version 1.3.0. Starting from numpy 1.3.0, we are working on separating the pure C, computational code
from the python dependent code. The goal is twofolds: making the code cleaner, and enabling code reuse by other
extensions outside numpy (scipy, etc...).
The numpy core math library (npymath) is a first step in this direction. This library contains most math-related C99
functionality, which can be used on platforms where C99 is not well supported. The core math functions have the
same API as the C99 ones, except for the npy_* prefix.
The available functions are defined in npy_math.h - please refer to this header in doubt.
NPY_NAN
This macro is defined to a NaN (Not a Number), and is guaranteed to have the signbit unset (positive NaN).
The corresponding single and extension precision macro are available with the suffix F and L.
NPY_INFINITY
This macro is defined to a positive inf. The corresponding single and extension precision macro are available
with the suffix F and L.
NPY_PZERO
This macro is defined to positive zero. The corresponding single and extension precision macro are available
with the suffix F and L.
NPY_NZERO
This macro is defined to negative zero (that is with the sign bit set). The corresponding single and extension
precision macro are available with the suffix F and L.
int npy_isnan(x)
This is a macro, and is equivalent to C99 isnan: works for single, double and extended precision, and return a
non 0 value is x is a NaN.
int npy_isfinite(x)
This is a macro, and is equivalent to C99 isfinite: works for single, double and extended precision, and return a
non 0 value is x is neither a NaN or a infinity.
int npy_isinf(x)
This is a macro, and is equivalent to C99 isinf: works for single, double and extended precision, and return a
non 0 value is x is infinite (positive and negative).
int npy_signbit(x)
This is a macro, and is equivalent to C99 signbit: works for single, double and extended precision, and return a
non 0 value is x has the signbit set (that is the number is negative).
double npy_copysign(double x, double y)
This is a function equivalent to C99 copysign: return x with the same sign as y. Works for any value, including
inf and nan. Single and extended precisions are available with suffix f and l. New in version 1.4.0.
The following math constants are available in npy_math.h. Single and extended precision are also available by adding
the F and L suffixes respectively.
NPY_E
Base of natural logarithm (e)
NPY_LOG2E
ln(e)
Logarithm to base 2 of the Euler constant ( ln(2) )
NPY_LOG10E
ln(e)
Logarithm to base 10 of the Euler constant ( ln(10) )
NPY_LOGE2
Natural logarithm of 2 (ln(2))
NPY_LOGE10
Natural logarithm of 10 (ln(10))
NPY_PI
Pi ()
NPY_PI_2
Pi divided by 2 ( 2 )
NPY_PI_4
Pi divided by 4 ( 4 )
NPY_1_PI
Reciprocal of pi ( 1 )
NPY_2_PI
Two times the reciprocal of pi ( 2 )
NPY_EULER
Complex functions
New in version 1.4.0. C99-like complex functions have been added. Those can be used if you wish to implement
portable C extensions. Since we still support platforms without C99 complex type, you need to restrict to C90-
compatible syntax, e.g.:
/* a = 1 + 2i \*/
npy_complex a = npy_cpack(1, 2);
npy_complex b;
b = npy_log(a);
New in version 1.4.0. To use the core math library in your own extension, you need to add the npymath compile and
link options to your extension in your setup.py:
In other words, the usage of info is exactly the same as when using blas_info and co.
SIX
NUMPY INTERNALS
Fanaticism consists of redoubling your efforts when you have forgotten your aim. George Santayana
An authority is a person who can tell you more about something than you really care to know. Unknown
This Chapter attempts to explain the logic behind some of the new pieces of code. The purpose behind these explana-
tions is to enable somebody to be able to understand the ideas behind the implementation somewhat more easily than
just staring at the code. Perhaps in this way, the algorithms can be improved on, borrowed from, and/or optimized.
One fundamental aspect of the ndarray is that an array is seen as a chunk of memory starting at some location. The
interpretation of this memory depends on the stride information. For each dimension in an N -dimensional array, an
integer (stride) dictates how many bytes must be skipped to get to the next element in that dimension. Unless you have
a single-segment array, this stride information must be consulted when traversing through an array. It is not difficult
to write code that accepts strides, you just have to use (char *) pointers because strides are in units of bytes. Keep
in mind also that strides do not have to be unit-multiples of the element size. Also, remember that if the number of
dimensions of the array is 0 (sometimes called a rank-0 array), then the strides and dimensions variables are NULL.
Besides the structural information contained in the strides and dimensions members of the PyArrayObject, the
flags contain important information about how the data may be accessed. In particular, the NPY_ALIGNED flag is set
when the memory is on a suitable boundary according to the data-type array. Even if you have a contiguous chunk
of memory, you cannot just assume it is safe to dereference a data- type-specific pointer to an element. Only if the
NPY_ALIGNED flag is set is this a safe operation (on some platforms it will work but on others, like Solaris, it will
cause a bus error). The NPY_WRITEABLE should also be ensured if you plan on writing to the memory area of
the array. It is also possible to obtain a pointer to an unwriteable memory area. Sometimes, writing to the memory
area when the NPY_WRITEABLE flag is not set will just be rude. Other times it can cause program crashes ( e.g. a
data-area that is a read-only memory-mapped file).
The data-type is an important abstraction of the ndarray. Operations will look to the data-type to provide the key
functionality that is needed to operate on the array. This functionality is provided in the list of function pointers
pointed to by the f member of the PyArray_Descr structure. In this way, the number of data-types can be
extended simply by providing a PyArray_Descr structure with suitable function pointers in the f member. For
built-in types there are some optimizations that by-pass this mechanism, but the point of the data- type abstraction is
to allow new data-types to be added.
1075
NumPy Reference, Release 2.0.0.dev8464
One of the built-in data-types, the void data-type allows for arbitrary records containing 1 or more fields as elements
of the array. A field is simply another data-type object along with an offset into the current record. In order to
support arbitrarily nested fields, several recursive implementations of data-type access are implemented for the void
type. A common idiom is to cycle through the elements of the dictionary and perform a specific operation based on
the data-type object stored at the given offset. These offsets can be arbitrary numbers. Therefore, the possibility of
encountering mis- aligned data must be recognized and taken into account if necessary.
A very common operation in much of NumPy code is the need to iterate over all the elements of a general, strided,
N-dimensional array. This operation of a general-purpose N-dimensional loop is abstracted in the notion of an iterator
object. To write an N-dimensional loop, you only have to create an iterator object from an ndarray, work with the
dataptr member of the iterator object structure and call the macro PyArray_ITER_NEXT (it) on the iterator object
to move to the next element. The next element is always in C-contiguous order. The macro works by first special
casing the C-contiguous, 1-D, and 2-D cases which work very simply.
For the general case, the iteration works by keeping track of a list of coordinate counters in the iterator object. At each
iteration, the last coordinate counter is increased (starting from 0). If this counter is smaller then one less than the size
of the array in that dimension (a pre-computed and stored value), then the counter is increased and the dataptr member
is increased by the strides in that dimension and the macro ends. If the end of a dimension is reached, the counter
for the last dimension is reset to zero and the dataptr is moved back to the beginning of that dimension by subtracting
the strides value times one less than the number of elements in that dimension (this is also pre-computed and stored
in the backstrides member of the iterator object). In this case, the macro does not end, but a local dimension counter
is decremented so that the next-to-last dimension replaces the role that the last dimension played and the previously-
described tests are executed again on the next-to-last dimension. In this way, the dataptr is adjusted appropriately for
arbitrary striding.
The coordinates member of the PyArrayIterObject structure maintains the current N-d counter unless
the underlying array is C-contiguous in which case the coordinate counting is by-passed. The index mem-
ber of the PyArrayIterObject keeps track of the current flat index of the iterator. It is updated by the
PyArray_ITER_NEXT macro.
6.1.4 Broadcasting
In Numeric, broadcasting was implemented in several lines of code buried deep in ufuncobject.c. In NumPy, the
notion of broadcasting has been abstracted so that it can be performed in multiple places. Broadcasting is handled by
the function PyArray_Broadcast. This function requires a PyArrayMultiIterObject (or something that
is a binary equivalent) to be passed in. The PyArrayMultiIterObject keeps track of the broadcasted number
of dimensions and size in each dimension along with the total size of the broadcasted result. It also keeps track of the
number of arrays being broadcast and a pointer to an iterator for each of the arrays being broadcasted.
The PyArray_Broadcast function takes the iterators that have already been defined and uses them to determine
the broadcast shape in each dimension (to create the iterators at the same time that broadcasting occurs then use the
PyMultiIter_New function). Then, the iterators are adjusted so that each iterator thinks it is iterating over an
array with the broadcasted size. This is done by adjusting the iterators number of dimensions, and the shape in each
dimension. This works because the iterator strides are also adjusted. Broadcasting only adjusts (or adds) length-1
dimensions. For these dimensions, the strides variable is simply set to 0 so that the data-pointer for the iterator over
that array doesnt move as the broadcasting operation operates over the extended dimension.
Broadcasting was always implemented in Numeric using 0-valued strides for the extended dimensions. It
is done in exactly the same way in NumPy. The big difference is that now the array of strides is kept
track of in a PyArrayIterObject, the iterators involved in a broadcasted result are kept track of in a
PyArrayMultiIterObject, and the PyArray_BroadCast call implements the broad-casting rules.
The array scalars offer a hierarchy of Python types that allow a one- to-one correspondence between the data-type
stored in an array and the Python-type that is returned when an element is extracted from the array. An exception to
this rule was made with object arrays. Object arrays are heterogeneous collections of arbitrary Python objects. When
you select an item from an object array, you get back the original Python object (and not an object array scalar which
does exist but is rarely used for practical purposes).
The array scalars also offer the same methods and attributes as arrays with the intent that the same code can be
used to support arbitrary dimensions (including 0-dimensions). The array scalars are read-only (immutable) with
the exception of the void scalar which can also be written to so that record-array field setting works more naturally
(a[0][f1] = value ).
The implementation of advanced indexing represents some of the most difficult code to write and explain. In fact, there
are two implementations of advanced indexing. The first works only with 1-D arrays and is implemented to handle
expressions involving a.flat[obj]. The second is general-purpose that works for arrays of arbitrary dimension (up to
a fixed maximum). The one-dimensional indexing approaches were implemented in a rather straightforward fashion,
and so it is the general-purpose indexing code that will be the focus of this section.
There is a multi-layer approach to indexing because the indexing code can at times return an array scalar and at other
times return an array. The functions with _nice appended to their name do this special handling while the function
without the _nice appendage always return an array (perhaps a 0-dimensional array). Some special-case optimizations
(the index being an integer scalar, and the index being a tuple with as many dimensions as the array) are handled in
array_subscript_nice function which is what Python calls when presented with the code a[obj]. These optimizations
allow fast single-integer indexing, and also ensure that a 0-dimensional array is not created only to be discarded as the
array scalar is returned instead. This provides significant speed-up for code that is selecting many scalars out of an
array (such as in a loop). However, it is still not faster than simply using a list to store standard Python scalars, because
that is optimized by the Python interpreter itself.
After these optimizations, the array_subscript function itself is called. This function first checks for field selection
which occurs when a string is passed as the indexing object. Then, 0-D arrays are given special-case consideration.
Finally, the code determines whether or not advanced, or fancy, indexing needs to be performed. If fancy indexing
is not needed, then standard view-based indexing is performed using code borrowed from Numeric which parses the
indexing object and returns the offset into the data-buffer and the dimensions necessary to create a new view of the
array. The strides are also changed by multiplying each stride by the step-size requested along the corresponding
dimension.
Fancy-indexing check
The fancy_indexing_check routine determines whether or not to use standard view-based indexing or new copy-based
indexing. If the indexing object is a tuple, then view-based indexing is assumed by default. Only if the tuple contains
an array object or a sequence object is fancy-indexing assumed. If the indexing object is an array, then fancy indexing
is automatically assumed. If the indexing object is any other kind of sequence, then fancy-indexing is assumed by
default. This is over-ridden to simple indexing if the sequence contains any slice, newaxis, or Ellipsis objects, and no
arrays or additional sequences are also contained in the sequence. The purpose of this is to allow the construction of
slicing sequences which is a common technique for building up code that works in arbitrary numbers of dimensions.
Fancy-indexing implementation
The concept of indexing was also abstracted using the idea of an iterator. If fancy indexing is performed, then a
PyArrayMapIterObject is created. This internal object is not exposed to Python. It is created in order to handle
the fancy-indexing at a high-level. Both get and set fancy-indexing operations are implemented using this object. Fancy
indexing is abstracted into three separate operations: (1) creating the PyArrayMapIterObject from the indexing
object, (2) binding the PyArrayMapIterObject to the array being indexed, and (3) getting (or setting) the items
determined by the indexing object. There is an optimization implemented so that the PyArrayIterObject (which
has its own less complicated fancy-indexing) is used for indexing when possible.
Universal functions are callable objects that take N inputs and produce M outputs by wrapping basic 1-D loops that
work element-by-element into full easy-to use functions that seamlessly implement broadcasting, type-checking and
buffered coercion, and output-argument handling. New universal functions are normally created in C, although there
is a mechanism for creating ufuncs from Python functions (frompyfunc). The user must supply a 1-D loop that
implements the basic function taking the input scalar values and placing the resulting scalars into the appropriate
output slots as explaine n implementation.
Setup
Every ufunc calculation involves some overhead related to setting up the calculation. The practical significance of
this overhead is that even though the actual calculation of the ufunc is very fast, you will be able to write array
and type-specific code that will work faster for small arrays than the ufunc. In particular, using ufuncs to perform
many calculations on 0-D arrays will be slower than other Python-based solutions (the silently-imported scalarmath
module exists precisely to give array scalars the look-and-feel of ufunc-based calculations with significantly reduced
overhead).
When a ufunc is called, many things must be done. The information collected from these setup operations is stored
in a loop-object. This loop object is a C-structure (that could become a Python object but is not initialized as such
because it is only used internally). This loop object has the layout needed to be used with PyArray_Broadcast so that
the broadcasting can be handled in the same way as it is handled in other sections of code.
The first thing done is to look-up in the thread-specific global dictionary the current values for the buffer-size, the error
mask, and the associated error object. The state of the error mask controls what happens when an error-condiction is
found. It should be noted that checking of the hardware error flags is only performed after each 1-D loop is executed.
This means that if the input and output arrays are contiguous and of the correct type so that a single 1-D loop is
performed, then the flags may not be checked until all elements of the array have been calcluated. Looking up these
values in a thread- specific dictionary takes time which is easily ignored for all but very small arrays.
After checking, the thread-specific global variables, the inputs are evaluated to determine how the ufunc should proceed
and the input and output arrays are constructed if necessary. Any inputs which are not arrays are converted to arrays
(using context if necessary). Which of the inputs are scalars (and therefore converted to 0-D arrays) is noted.
Next, an appropriate 1-D loop is selected from the 1-D loops available to the ufunc based on the input array types. This
1-D loop is selected by trying to match the signature of the data-types of the inputs against the available signatures.
The signatures corresponding to built-in types are stored in the types member of the ufunc structure. The signatures
corresponding to user-defined types are stored in a linked-list of function-information with the head element stored
as a CObject in the userloops dictionary keyed by the data-type number (the first user-defined type in the argument
list is used as the key). The signatures are searched until a signature is found to which the input arrays can all be cast
safely (ignoring any scalar arguments which are not allowed to determine the type of the result). The implication of
this search procedure is that lesser types should be placed below larger types when the signatures are stored. If no
1-D loop is found, then an error is reported. Otherwise, the argument_list is updated with the stored signature in
case casting is necessary and to fix the output types assumed by the 1-D loop.
If the ufunc has 2 inputs and 1 output and the second input is an Object array then a special-case check is performed
so that NotImplemented is returned if the second input is not an ndarray, has the __array_priority__ attribute, and
has an __r{op}__ special method. In this way, Python is signaled to give the other object a chance to complete the
operation instead of using generic object-array calculations. This allows (for example) sparse matrices to override the
multiplication operator 1-D loop.
For input arrays that are smaller than the specified buffer size, copies are made of all non-contiguous, mis-aligned, or
out-of- byteorder arrays to ensure that for small arrays, a single-loop is used. Then, array iterators are created for all
the input arrays and the resulting collection of iterators is broadcast to a single shape.
The output arguments (if any) are then processed and any missing return arrays are constructed. If any provided output
array doesnt have the correct type (or is mis-aligned) and is smaller than the buffer size, then a new output array is
constructed with the special UPDATEIFCOPY flag set so that when it is DECREFd on completion of the function,
its contents will be copied back into the output array. Iterators for the output arguments are then processed.
Finally, the decision is made about how to execute the looping mechanism to ensure that all elements of the input
arrays are combined to produce the output arrays of the correct type. The options for loop execution are one-loop (for
contiguous, aligned, and correct data- type), strided-loop (for non-contiguous but still aligned and correct data-type),
and a buffered loop (for mis-aligned or incorrect data- type situations). Depending on which execution method is
called for, the loop is then setup and computed.
Function call
This section describes how the basic universal function computation loop is setup and executed for each of the three
different kinds of execution possibilities. If NPY_ALLOW_THREADS is defined during compilation, then the Python
Global Interpreter Lock (GIL) is released prior to calling all of these loops (as long as they dont involve object arrays).
It is re-acquired if necessary to handle error conditions. The hardware error flags are checked only after the 1-D loop
is calcluated.
One Loop
This is the simplest case of all. The ufunc is executed by calling the underlying 1-D loop exactly once. This is possible
only when we have aligned data of the correct type (including byte-order) for both input and output and all arrays have
uniform strides (either contiguous, 0-D, or 1-D). In this case, the 1-D computational loop is called once to compute
the calculation for the entire array. Note that the hardware error flags are only checked after the entire calculation is
complete.
Strided Loop
When the input and output arrays are aligned and of the correct type, but the striding is not uniform (non-contiguous
and 2-D or larger), then a second looping structure is employed for the calculation. This approach converts all of the
iterators for the input and output arguments to iterate over all but the largest dimension. The inner loop is then handled
by the underlying 1-D computational loop. The outer loop is a standard iterator loop on the converted iterators. The
hardware error flags are checked after each 1-D loop is completed.
Buffered Loop
This is the code that handles the situation whenever the input and/or output arrays are either misaligned or of the wrong
data-type (including being byte-swapped) from what the underlying 1-D loop expects. The arrays are also assumed to
be non-contiguous. The code works very much like the strided loop except for the inner 1-D loop is modified so that
pre-processing is performed on the inputs and post- processing is performed on the outputs in bufsize chunks (where
bufsize is a user-settable parameter). The underlying 1-D computational loop is called on data that is copied over (if it
needs to be). The setup code and the loop code is considerably more complicated in this case because it has to handle:
memory allocation of the temporary buffers
deciding whether or not to use buffers on the input and output data (mis-aligned and/or wrong data-type)
copying and possibly casting data for any inputs or outputs for which buffers are necessary.
special-casing Object arrays so that reference counts are properly handled when copies and/or casts are neces-
sary.
breaking up the inner 1-D loop into bufsize chunks (with a possible remainder).
Again, the hardware error flags are checked at the end of each 1-D loop.
Ufuncs allow other array-like classes to be passed seamlessly through the interface in that inputs of a particu-
lar class will induce the outputs to be of that same class. The mechanism by which this works is the following.
If any of the inputs are not ndarrays and define the __array_wrap__ method, then the class with the largest
__array_priority__ attribute determines the type of all the outputs (with the exception of any output arrays
passed in). The __array_wrap__ method of the input array will be called with the ndarray being returned from
the ufunc as its input. There are two calling styles of the __array_wrap__ function supported. The first takes
the ndarray as the first argument and a tuple of context as the second argument. The context is (ufunc, arguments,
output argument number). This is the first call tried. If a TypeError occurs, then the function is called with just the
ndarray as the first argument.
Methods
Their are three methods of ufuncs that require calculation similar to the general-purpose ufuncs. These are reduce,
accumulate, and reduceat. Each of these methods requires a setup command followed by a loop. There are four loop
styles possible for the methods corresponding to no-elements, one-element, strided-loop, and buffered- loop. These
are the same basic loop styles as implemented for the general purpose function call except for the no-element and one-
element cases which are special-cases occurring when the input array objects have 0 and 1 elements respectively.
Setup
The setup function for all three methods is construct_reduce. This function creates a reducing loop object and
fills it with parameters needed to complete the loop. All of the methods only work on ufuncs that take 2-inputs and
return 1 output. Therefore, the underlying 1-D loop is selected assuming a signature of [ otype, otype, otype
] where otype is the requested reduction data-type. The buffer size and error handling is then retrieved from (per-
thread) global storage. For small arrays that are mis-aligned or have incorrect data-type, a copy is made so that the
un-buffered section of code is used. Then, the looping strategy is selected. If there is 1 element or 0 elements in the
array, then a simple looping method is selected. If the array is not mis-aligned and has the correct data-type, then
strided looping is selected. Otherwise, buffered looping must be performed. Looping parameters are then established,
and the return array is constructed. The output array is of a different shape depending on whether the method is reduce,
accumulate, or reduceat. If an output array is already provided, then its shape is checked. If the output array is not
C-contiguous, aligned, and of the correct data type, then a temporary copy is made with the UPDATEIFCOPY flag set.
In this way, the methods will be able to work with a well-behaved output array but the result will be copied back into
the true output array when the method computation is complete. Finally, iterators are set up to loop over the correct
axis (depending on the value of axis provided to the method) and the setup routine returns to the actual computation
routine.
Reduce
All of the ufunc methods use the same underlying 1-D computational loops with input and output arguments adjusted
so that the appropriate reduction takes place. For example, the key to the functioning of reduce is that the 1-D loop is
called with the output and the second input pointing to the same position in memory and both having a step- size of 0.
The first input is pointing to the input array with a step- size given by the appropriate stride for the selected axis. In
this way, the operation performed is
o= i[0]
o= i[k]<op>o k = 1...N
where N + 1 is the number of elements in the input, i, o is the output, and i[k] is the k th element of i along the selected
axis. This basic operations is repeated for arrays with greater than 1 dimension so that the reduction takes place for
every 1-D sub-array along the selected axis. An iterator with the selected dimension removed handles this looping.
For buffered loops, care must be taken to copy and cast data before the loop function is called because the underlying
loop expects aligned data of the correct data-type (including byte-order). The buffered loop must handle this copying
and casting prior to calling the loop function on chunks no greater than the user-specified bufsize.
Accumulate
The accumulate function is very similar to the reduce function in that the output and the second input both point to the
output. The difference is that the second input points to memory one stride behind the current output pointer. Thus,
the operation performed is
o[0] = i[0]
o[k] = i[k]<op>o[k 1] k = 1 . . . N.
The output has the same shape as the input and each 1-D loop operates over N elements when the shape in the selected
axis is N +1. Again, buffered loops take care to copy and cast the data before calling the underlying 1-D computational
loop.
Reduceat
The reduceat function is a generalization of both the reduce and accumulate functions. It implements a reduce over
ranges of the input array specified by indices. The extra indices argument is checked to be sure that every input
is not too large for the input array along the selected dimension before the loop calculations take place. The loop
implementation is handled using code that is very similar to the reduce code repeated as many times as there are
elements in the indices input. In particular: the first input pointer passed to the underlying 1-D computational loop
points to the input array at the correct location indicated by the index array. In addition, the output pointer and the
second input pointer passed to the underlying 1-D loop point to the same position in memory. The size of the 1-D
computational loop is fixed to be the difference between the current index and the next index (when the current index
is the last index, then the next index is assumed to be the length of the array along the selected dimension). In this
way, the 1-D loop will implement a reduce over the specified indices.
Mis-aligned or a loop data-type that does not match the input and/or output data-type is handled using buffered code
where-in data is copied to a temporary buffer and cast to the correct data-type if necessary prior to calling the under-
lying 1-D function. The temporary buffers are created in (element) sizes no bigger than the user settable buffer-size
value. Thus, the loop must be flexible enough to call the underlying 1-D computational loop enough times to complete
the total calculation in chunks no bigger than the buffer-size.
It helps to understand a bit about how numpy arrays are handled under the covers to help understand numpy better.
This section will not go into great detail. Those wishing to understand the full details are referred to Travis Oliphants
book Guide to Numpy.
Numpy arrays consist of two major components, the raw array data (from now on, referred to as the data buffer), and
the information about the raw array data. The data buffer is typically what people think of as arrays in C or Fortran,
a contiguous (and fixed) block of memory containing fixed sized data items. Numpy also contains a significant set of
data that describes how to interpret the data in the data buffer. This extra information contains (among other things):
1. The basic data elements size in bytes
2. The start of the data within the data buffer (an offset relative to the beginning of the data buffer).
3. The number of dimensions and the size of each dimension
4. The separation between elements for each dimension (the stride). This does not have to be a multiple of the
element size
5. The byte order of the data (which may not be the native byte order)
6. Whether the buffer is read-only
7. Information (via the dtype object) about the interpretation of the basic data element. The basic data element
may be as simple as a int or a float, or it may be a compound object (e.g., struct-like), a fixed character field, or
Python object pointers.
8. Whether the array is to interpreted as C-order or Fortran-order.
This arrangement allow for very flexible use of arrays. One thing that it allows is simple changes of the metadata
to change the interpretation of the array buffer. Changing the byteorder of the array is a simple change involving no
rearrangement of the data. The shape of the array can be changed very easily without changing anything in the data
buffer or any data copying at all
Among other things that are made possible is one can create a new array metadata object that uses the same data buffer
to create a new view of that data buffer that has a different interpretation of the buffer (e.g., different shape, offset,
byte order, strides, etc) but shares the same data bytes. Many operations in numpy do just this such as slices. Other
operations, such as transpose, dont move data elements around in the array, but rather change the information about
the shape and strides so that the indexing of the array changes, but the data in the doesnt move.
Typically these new versions of the array metadata but the same data buffer are new views into the data buffer. There
is a different ndarray object, but it uses the same data buffer. This is why it is necessary to force copies through use of
the .copy() method if one really wants to make a new and independent copy of the data buffer.
New views into arrays mean the the object reference counts for the data buffer increase. Simply doing away with the
original array object will not remove the data buffer if other views of it still exist.
What is the right way to index multi-dimensional arrays? Before you jump to conclusions about the one and true
way to index multi-dimensional arrays, it pays to understand why this is a confusing issue. This section will try to
explain in detail how numpy indexing works and why we adopt the convention we do for images, and when it may be
appropriate to adopt other conventions.
The first thing to understand is that there are two conflicting conventions for indexing 2-dimensional arrays. Matrix
notation uses the first index to indicate which row is being selected and the second index to indicate which column
is selected. This is opposite the geometrically oriented-convention for images where people generally think the first
index represents x position (i.e., column) and the second represents y position (i.e., row). This alone is the source of
much confusion; matrix-oriented users and image-oriented users expect two different things with regard to indexing.
The second issue to understand is how indices correspond to the order the array is stored in memory. In Fortran the first
index is the most rapidly varying index when moving through the elements of a two dimensional array as it is stored
in memory. If you adopt the matrix convention for indexing, then this means the matrix is stored one column at a time
(since the first index moves to the next row as it changes). Thus Fortran is considered a Column-major language. C
has just the opposite convention. In C, the last index changes most rapidly as one moves through the array as stored
in memory. Thus C is a Row-major language. The matrix is stored by rows. Note that in both cases it presumes that
the matrix convention for indexing is being used, i.e., for both Fortran and C, the first index is the row. Note this
convention implies that the indexing convention is invariant and that the data order changes to keep that so.
But thats not the only way to look at it. Suppose one has large two-dimensional arrays (images or matrices) stored
in data files. Suppose the data are stored by rows rather than by columns. If we are to preserve our index convention
(whether matrix or image) that means that depending on the language we use, we may be forced to reorder the data
if it is read into memory to preserve our indexing convention. For example if we read row-ordered data into memory
without reordering, it will match the matrix indexing convention for C, but not for Fortran. Conversely, it will match
the image indexing convention for Fortran, but not for C. For C, if one is using data stored in row order, and one wants
to preserve the image index convention, the data must be reordered when reading into memory.
In the end, which you do for Fortran or C depends on which is more important, not reordering data or preserving the
indexing convention. For large images, reordering data is potentially expensive, and often the indexing convention is
inverted to avoid that.
The situation with numpy makes this issue yet more complicated. The internal machinery of numpy arrays is flexible
enough to accept any ordering of indices. One can simply reorder indices by manipulating the internal stride infor-
mation for arrays without reordering the data at all. Numpy will know how to map the new index order to the data
without moving the data.
So if this is true, why not choose the index order that matches what you most expect? In particular, why not define
row-ordered images to use the image convention? (This is sometimes referred to as the Fortran convention vs the C
convention, thus the C and FORTRAN order options for array ordering in numpy.) The drawback of doing this
is potential performance penalties. Its common to access the data sequentially, either implicitly in array operations
or explicitly by looping over rows of an image. When that is done, then the data will be accessed in non-optimal
order. As the first index is incremented, what is actually happening is that elements spaced far apart in memory are
being sequentially accessed, with usually poor memory access speeds. For example, for a two dimensional image im
defined so that im[0, 10] represents the value at x=0, y=10. To be consistent with usual Python behavior then im[0]
would represent a column at x=0. Yet that data would be spread over the whole array since the data are stored in
row order. Despite the flexibility of numpys indexing, it cant really paper over the fact basic operations are rendered
inefficient because of data order or that getting contiguous subarrays is still awkward (e.g., im[:,0] for the first row,
vs im[0]), thus one cant use an idiom such as for row in im; for col in im does work, but doesnt yield contiguous
column data.
As it turns out, numpy is smart enough when dealing with ufuncs to determine which index is the most rapidly varying
one in memory and uses that for the innermost loop. Thus for ufuncs there is no large intrinsic advantage to either
approach in most cases. On the other hand, use of .flat with an FORTRAN ordered array will lead to non-optimal
memory access as adjacent elements in the flattened array (iterator, actually) are not contiguous in memory.
Indeed, the fact is that Python indexing on lists and other sequences naturally leads to an outside-to inside ordering
(the first index gets the largest grouping, the next the next largest, and the last gets the smallest element). Since image
data are normally stored by rows, this corresponds to position within rows being the last item indexed.
If you do want to use Fortran ordering realize that there are two approaches to consider: 1) accept that the first index
is just not the most rapidly changing in memory and have all your I/O routines reorder your data when going from
memory to disk or visa versa, or use numpys mechanism for mapping the first index to the most rapidly varying
data. We recommend the former if possible. The disadvantage of the latter is that many of numpys functions will
yield arrays without Fortran ordering unless you are careful to use the order keyword. Doing this would be highly
inconvenient.
Otherwise we recommend simply learning to reverse the usual order of indices when accessing elements of an array.
Granted, it goes against the grain, but it is more in line with Python semantics and the natural order of the data.
SEVEN
ACKNOWLEDGEMENTS
Large parts of this manual originate from Travis E. Oliphants book Guide to Numpy (which generously entered Public
Domain in August 2008). The reference documentation for many of the functions are written by numerous contributors
and developers of Numpy, both prior to and during the Numpy Documentation Marathon.
Please help to improve NumPys documentation! Instructions on how to join the ongoing documentation marathon
can be found on the scipy.org website
1085
NumPy Reference, Release 2.0.0.dev8464
[R57] : G. H. Golub and C. F. van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University
Press, 1996, pg. 8.
[R58] : G. H. Golub and C. F. van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University
Press, 1996, pg. 8.
[R61] Wikipedia, Vandermonde matrix, http://en.wikipedia.org/wiki/Vandermonde_matrix
[R59] Wikipedia, Curve fitting, http://en.wikipedia.org/wiki/Curve_fitting
[R60] Wikipedia, Polynomial interpolation, http://en.wikipedia.org/wiki/Polynomial_interpolation
[R269] http://en.wikipedia.org/wiki/IEEE_754
[R276] Wikipedia, Vandermonde matrix, http://en.wikipedia.org/wiki/Vandermonde_matrix
[R1] Press, Teukolsky, Vetterling and Flannery, Numerical Recipes in C++, 2nd ed, Cambridge University Press,
2002, p. 31.
[R268] Format Specification Mini-Language, Python Documentation.
[R23] Wikipedia, Twos complement, http://en.wikipedia.org/wiki/Twos_complement
[CT] Cooley, James W., and John W. Tukey, 1965, An algorithm for the machine calculation of complex Fourier
series, Math. Comput. 19: 297-301.
[CT] Cooley, James W., and John W. Tukey, 1965, An algorithm for the machine calculation of complex Fourier
series, Math. Comput. 19: 297-301.
[NR] Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P., 2007, Numerical Recipes: The Art of Scientific
Computing, ch. 12-13. Cambridge Univ. Press, Cambridge, UK.
[R63] : G. H. Golub and C. F. van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University
Press, 1996, pg. 8.
[R47] G. Strang, Linear Algebra and Its Applications, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pg. 222.
[R48] G. H. Golub and C. F. Van Loan, Matrix Computations, Baltimore, MD, Johns Hopkins University Press, 1985,
pg. 15
[R46] G. Strang, Linear Algebra and Its Applications, Orlando, FL, Academic Press, Inc., 1980, pg. 285.
[R50] G. Strang, Linear Algebra and Its Applications, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pg. 22.
[R49] G. Strang, Linear Algebra and Its Applications, 2nd Ed., Orlando, FL, Academic Press, Inc., 1980, pp. 139-
142.
[R69] Dalgaard, Peter, Introductory Statistics with R, Springer-Verlag, 2002.
1087
NumPy Reference, Release 2.0.0.dev8464
1088 Bibliography
NumPy Reference, Release 2.0.0.dev8464
Bibliography 1089
NumPy Reference, Release 2.0.0.dev8464
1090 Bibliography
NumPy Reference, Release 2.0.0.dev8464
[R190] Abramowitz, M. and Stegun, I. A. (Eds.). Handbook of Mathematical Functions with Formulas, Graphs, and
Mathematical Tables, 9th printing. New York: Dover, 1972.
[R191] The Laplace distribution and generalizations By Samuel Kotz, Tomasz J. Kozubowski, Krzysztof Podgorski,
Birkhauser, 2001.
[R192] Weisstein, Eric W. Laplace Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/LaplaceDistribution.html
[R193] Wikipedia, Laplace distribution, http://en.wikipedia.org/wiki/Laplace_distribution
[R194] Reiss, R.-D. and Thomas M. (2001), Statistical Analysis of Extreme Values, from Insurance, Finance, Hy-
drology and Other Fields, Birkhauser Verlag, Basel, pp 132-133.
[R195] Weisstein, Eric W. Logistic Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/LogisticDistribution.html
[R196] Wikipedia, Logistic-distribution, http://en.wikipedia.org/wiki/Logistic-distribution
[R197] Eckhard Limpert, Werner A. Stahel, and Markus Abbt, Log-normal Distributions across the Sciences: Keys
and Clues, May 2001 Vol. 51 No. 5 BioScience http://stat.ethz.ch/~stahel/lognormal/bioscience.pdf
[R198] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme Values, Birkhauser Verlag, Basel, pp 31-32.
[R199] Wikipedia, Lognormal distribution, http://en.wikipedia.org/wiki/Lognormal_distribution
[R200] Buzas, Martin A.; Culver, Stephen J., Understanding regional species diversity through the log series distri-
bution of occurrences: BIODIVERSITY RESEARCH Diversity & Distributions, Volume 5, Number 5, September
1999 , pp. 187-195(9).
[R201] Fisher, R.A A.S. Corbet, and C.B. Williams. 1943. The relation between the number of species and the
number of individuals in a random sample of an animal population. Journal of Animal Ecology, 12:42-58.
[R202] D. J. Hand, F. Daly, D. Lunn, E. Ostrowski, A Handbook of Small Data Sets, CRC Press, 1994.
[R203] Wikipedia, Logarithmic-distribution, http://en.wikipedia.org/wiki/Logarithmic-distribution
[R204] A. Papoulis, Probability, Random Variables, and Stochastic Processes, 3rd ed., McGraw-Hill Companies,
1991
[R205] R.O. Duda, P.E. Hart, and D.G. Stork, Pattern Classification, 2nd ed., Wiley, 2001.
[R206] Weisstein, Eric W. Negative Binomial Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/NegativeBinomialDistribution.html
[R207] Wikipedia, Negative binomial distribution, http://en.wikipedia.org/wiki/Negative_binomial_distribution
[R208] Delhi, M.S. Holla, On a noncentral chi-square distribution in the analysis of weapon systems effectiveness,
Metrika, Volume 15, Number 1 / December, 1970.
[R209] Wikipedia, Noncentral chi-square distribution http://en.wikipedia.org/wiki/Noncentral_chi-
square_distribution
[R210] Wikipedia, Normal distribution, http://en.wikipedia.org/wiki/Normal_distribution
[R211] P. R. Peebles Jr., Central Limit Theorem in Probability, Random Variables and Random Signal Principles,
4th ed., 2001, pp. 51, 51, 125.
[R212] Francis Hunt and Paul Johnson, On the Pareto Distribution of Sourceforge projects.
[R213] Pareto, V. (1896). Course of Political Economy. Lausanne.
[R214] Reiss, R.D., Thomas, M.(2001), Statistical Analysis of Extreme Values, Birkhauser Verlag, Basel, pp 23-30.
[R215] Wikipedia, Pareto distribution, http://en.wikipedia.org/wiki/Pareto_distribution
Bibliography 1091
NumPy Reference, Release 2.0.0.dev8464
[R216] Weisstein, Eric W. Poisson Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/PoissonDistribution.html
[R217] Wikipedia, Poisson distribution, http://en.wikipedia.org/wiki/Poisson_distribution
[R218] Christian Kleiber, Samuel Kotz, Statistical size distributions in economics and actuarial sciences, Wiley,
2003.
[R219] Heckert, N. A. and Filliben, James J. (2003). NIST Handbook 148: Dataplot Reference Manual, Volume
2: Let Subcommands and Library Functions, National Institute of Standards and Technology Handbook Series,
June 2003. http://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/powpdf.pdf
[R220] M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-dimensionally equidistributed uniform pseu-
dorandom number generator, ACM Trans. on Modeling and Computer Simulation, Vol. 8, No. 1, pp. 3-30, Jan.
1998.
[R221] Weisstein, Eric W. Gamma Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/GammaDistribution.html
[R222] Wikipedia, Gamma-distribution, http://en.wikipedia.org/wiki/Gamma-distribution
[R223] Dalgaard, Peter, Introductory Statistics With R, Springer, 2002.
[R224] Wikipedia, Students t-distribution http://en.wikipedia.org/wiki/Students_t-distribution
[R225] Abramowitz, M. and Stegun, I. A. (ed.), Handbook of Mathematical Functions, National Bureau of Standards,
1964; reprinted Dover Publications, 1965.
[R226] von Mises, Richard, 1964, Mathematical Theory of Probability and Statistics (New York: Academic Press).
[R227] Wikipedia, Von Mises distribution, http://en.wikipedia.org/wiki/Von_Mises_distribution
[R228] Waloddi Weibull, Professor, Royal Technical University, Stockholm, 1939 A Statistical Theory Of The
Strength Of Materials, Ingeniorsvetenskapsakademiens Handlingar Nr 151, 1939, Generalstabens Litografiska
Anstalts Forlag, Stockholm.
[R229] Waloddi Weibull, 1951 A Statistical Distribution Function of Wide Applicability, Journal Of Applied Me-
chanics ASME Paper.
[R230] Wikipedia, Weibull distribution, http://en.wikipedia.org/wiki/Weibull_distribution
[R231] Weisstein, Eric W. Zipf Distribution. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/ZipfDistribution.html
[R232] Wikipedia, Zeta distribution, http://en.wikipedia.org/wiki/Zeta_distribution
[R233] Wikipedia, Zipfs Law, http://en.wikipedia.org/wiki/Zipf%27s_law
[R234] Zipf, George Kingsley (1932): Selected Studies of the Principle of Relative Frequency in Language. Cam-
bridge (Mass.).
[R252] M. Matsumoto and T. Nishimura, Mersenne Twister: A 623-dimensionally equidistributed uniform pseu-
dorandom number generator, ACM Trans. on Modeling and Computer Simulation, Vol. 8, No. 1, pp. 3-30, Jan.
1998.
[R41] Wikipedia, Twos complement, http://en.wikipedia.org/wiki/Twos_complement
[R23] Wikipedia, Twos complement, http://en.wikipedia.org/wiki/Twos_complement
[R6] M. Abramowitz and I.A. Stegun, Handbook of Mathematical Functions, 10th printing, 1964, pp. 79.
http://www.math.sfu.ca/~cbm/aands/
[R7] Wikipedia, Inverse trigonometric function, http://en.wikipedia.org/wiki/Inverse_trigonometric_function
[R2] M. Abramowitz and I.A. Stegun, Handbook of Mathematical Functions, 10th printing, 1964, pp. 79.
http://www.math.sfu.ca/~cbm/aands/
1092 Bibliography
NumPy Reference, Release 2.0.0.dev8464
Bibliography 1093
NumPy Reference, Release 2.0.0.dev8464
[R270] Weisstein, Eric W. Sinc Function. From MathWorldA Wolfram Web Resource.
http://mathworld.wolfram.com/SincFunction.html
[R271] Wikipedia, Sinc function, http://en.wikipedia.org/wiki/Sinc_function
[R27] Wikipedia, Convolution, http://en.wikipedia.org/wiki/Convolution.
[R68] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng. trans. Ed.), Handbook of Mathematics, New
York, Van Nostrand Reinhold Co., 1985, pg. 720.
[R64] M. Sullivan and M. Sullivan, III, Algebra and Trignometry, Enhanced With Graphing Utilities, Prentice-Hall,
pg. 318, 1996.
[R65] G. Strang, Linear Algebra and Its Applications, 2nd Edition, Academic Press, pg. 182, 1980.
[R267] Wikipedia, Companion matrix, http://en.wikipedia.org/wiki/Companion_matrix
[R66] Wikipedia, Curve fitting, http://en.wikipedia.org/wiki/Curve_fitting
[R67] Wikipedia, Polynomial interpolation, http://en.wikipedia.org/wiki/Polynomial_interpolation
[WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Appli-
cations (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-
Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA.
[ODT Document]. Available: http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
OpenDocument-formula-20090508.odt
[WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Appli-
cations (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version, Pre-
Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA, USA.
[ODT Document]. Available: http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
OpenDocument-formula-20090508.odt
[G61] L. J. Gitman, Principles of Managerial Finance, Brief, 3rd ed., Addison-Wesley, 2003, pg. 346.
[WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document Format for Office Ap-
plications (OpenDocument)v1.2, Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
Pre-Draft 12. Organization for the Advancement of Structured Information Standards (OASIS). Billerica, MA,
USA. [ODT Document]. Available: http://www.oasis-open.org/committees/documents.php ?wg_abbrev=office-
formulaOpenDocument-formula-20090508.odt
[G41] L. J. Gitman, Principles of Managerial Finance, Brief, 3rd ed., Addison-Wesley, 2003, pg. 348.
[R18] M.S. Bartlett, Periodogram Analysis and Continuous Spectra, Biometrika 37, 1-16, 1950.
[R19] E.R. Kanasewich, Time Sequence Analysis in Geophysics, The University of Alberta Press, 1975, pp. 109-
110.
[R20] A.V. Oppenheim and R.W. Schafer, Discrete-Time Signal Processing, Prentice-Hall, 1999, pp. 468-471.
[R21] Wikipedia, Window function, http://en.wikipedia.org/wiki/Window_function
[R22] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, Numerical Recipes, Cambridge University
Press, 1986, page 429.
[R24] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.
[R25] Wikipedia, Window function, http://en.wikipedia.org/wiki/Window_function
[R26] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing. Upper Saddle River, NJ: Prentice-Hall,
1999, pp. 468-471.
[R30] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.
1094 Bibliography
NumPy Reference, Release 2.0.0.dev8464
[R31] E.R. Kanasewich, Time Sequence Analysis in Geophysics, The University of Alberta Press, 1975, pp. 109-
110.
[R32] Wikipedia, Window function, http://en.wikipedia.org/wiki/Window_function
[R33] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, Numerical Recipes, Cambridge University
Press, 1986, page 425.
[R34] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra, Dover Publications, New York.
[R35] E.R. Kanasewich, Time Sequence Analysis in Geophysics, The University of Alberta Press, 1975, pp. 106-
108.
[R36] Wikipedia, Window function, http://en.wikipedia.org/wiki/Window_function
[R37] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling, Numerical Recipes, Cambridge University
Press, 1986, page 425.
[R43] J. F. Kaiser, Digital Filters - Ch 7 in Systems analysis by digital computer, Editors: F.F. Kuo and J.F.
Kaiser, p 218-285. John Wiley and Sons, New York, (1966).
[R44] E.R. Kanasewich, Time Sequence Analysis in Geophysics, The University of Alberta Press, 1975, pp. 177-
178.
[R45] Wikipedia, Window function, http://en.wikipedia.org/wiki/Window_function
[R269] http://en.wikipedia.org/wiki/IEEE_754
[R57] : G. H. Golub and C. F. van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University
Press, 1996, pg. 8.
[R58] : G. H. Golub and C. F. van Loan, Matrix Computations, 3rd ed., Baltimore, MD, Johns Hopkins University
Press, 1996, pg. 8.
[R61] Wikipedia, Vandermonde matrix, http://en.wikipedia.org/wiki/Vandermonde_matrix
[R59] Wikipedia, Curve fitting, http://en.wikipedia.org/wiki/Curve_fitting
[R60] Wikipedia, Polynomial interpolation, http://en.wikipedia.org/wiki/Polynomial_interpolation
Bibliography 1095
NumPy Reference, Release 2.0.0.dev8464
1096 Bibliography
INDEX
1097
NumPy Reference, Release 2.0.0.dev8464
1098 Index
NumPy Reference, Release 2.0.0.dev8464
alterdot() (in module numpy), 946 argsort() (numpy.ma.MaskedArray method), 215, 344,
amax() (in module numpy), 693 921
amin() (in module numpy), 692 argsort() (numpy.matrix method), 101
angle() (in module numpy), 761 argsort() (numpy.ndarray method), 14, 54
anom (in module numpy.ma), 319, 896 argsort() (numpy.recarray method), 151
anom() (numpy.ma.MaskedArray method), 225, 331, 908 argsort() (numpy.record method), 168
anomalies (in module numpy.ma), 320, 897 argwhere() (in module numpy), 663
any (in module numpy.ma), 253, 831 arithmetic, 59, 235
any() (in module numpy), 669 around (in module numpy.ma), 357, 934
any() (numpy.generic method), 70 around() (in module numpy), 728
any() (numpy.ma.MaskedArray method), 225, 261, 839 array
any() (numpy.matrix method), 100 C-API, 1032
any() (numpy.ndarray method), 13, 59 interface, 366
any() (numpy.recarray method), 150 protocol, 366
any() (numpy.record method), 168 array iterator, 176, 1076
ao (C member), 1023 array scalars, 1077
append() (in module numpy), 449 array() (in module numpy), 395
appendpath() (in module numpy.distutils.misc_util), 1000 array() (in module numpy.core.defchararray), 147, 407
apply_along_axis() (in module numpy), 772 array() (in module numpy.core.records), 406
apply_along_axis() (in module numpy.ma), 361, 938 array() (in module numpy.ma), 181, 244, 822
apply_over_axes() (in module numpy), 773 array_equal() (in module numpy), 680
arange (in module numpy.ma), 362, 939 array_equiv() (in module numpy), 681
arange() (in module numpy), 409 array_repr() (in module numpy), 505
arccos (in module numpy), 716 array_split() (in module numpy), 441
arccosh (in module numpy), 726 array_str() (in module numpy), 506
arcsin (in module numpy), 715 as_array() (in module numpy.ctypeslib), 958
arcsinh (in module numpy), 726 as_ctypes() (in module numpy.ctypeslib), 958
arctan (in module numpy), 717 asanyarray() (in module numpy), 398, 432
arctan2 (in module numpy), 719 asanyarray() (in module numpy.ma), 183, 299, 876
arctanh (in module numpy), 727 asarray() (in module numpy), 396, 431
argmax() (in module numpy), 661 asarray() (in module numpy.core.defchararray), 408
argmax() (in module numpy.ma), 338, 915 asarray() (in module numpy.ma), 182, 298, 875
argmax() (numpy.generic method), 71 ascontiguousarray() (in module numpy), 399
argmax() (numpy.ma.MaskedArray method), 214, 340, asfarray() (in module numpy), 434
917 asfortranarray() (in module numpy), 434
argmax() (numpy.matrix method), 100 asmatrix() (in module numpy), 123, 399, 433
argmax() (numpy.ndarray method), 13, 56 asscalar() (in module numpy), 435
argmax() (numpy.recarray method), 151 assert_almost_equal() (in module numpy.testing), 947
argmax() (numpy.record method), 168 assert_approx_equal() (in module numpy.testing), 948
argmin() (in module numpy), 662 assert_array_almost_equal() (in module numpy.testing),
argmin() (in module numpy.ma), 338, 915 949
argmin() (numpy.generic method), 71 assert_array_equal() (in module numpy.testing), 950
argmin() (numpy.ma.MaskedArray method), 215, 340, assert_array_less() (in module numpy.testing), 951
917 assert_equal() (in module numpy.testing), 952
argmin() (numpy.matrix method), 101 assert_raises() (in module numpy.testing), 953
argmin() (numpy.ndarray method), 14, 56 assert_string_equal() (in module numpy.testing), 953
argmin() (numpy.recarray method), 151 assert_warns() (in module numpy.testing), 953
argmin() (numpy.record method), 168 astype() (numpy.chararray method), 130
argsort() (in module numpy), 658 astype() (numpy.core.defchararray.chararray method),
argsort() (in module numpy.ma), 342, 919 980
argsort() (numpy.chararray method), 131 astype() (numpy.generic method), 71
argsort() (numpy.core.defchararray.chararray method), astype() (numpy.ma.MaskedArray method), 207
981 astype() (numpy.matrix method), 102
argsort() (numpy.generic method), 71 astype() (numpy.ndarray method), 14, 43
Index 1099
NumPy Reference, Release 2.0.0.dev8464
1100 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1101
NumPy Reference, Release 2.0.0.dev8464
1102 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1103
NumPy Reference, Release 2.0.0.dev8464
1104 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1105
NumPy Reference, Release 2.0.0.dev8464
1106 Index
NumPy Reference, Release 2.0.0.dev8464
masked_less_equal() (in module numpy.ma), 187, 303, min() (numpy.record method), 171
880 minimum (in module numpy), 769
masked_not_equal() (in module numpy.ma), 188, 303, mintypecode() (in module numpy), 493
880 mirr() (in module numpy), 797
masked_object() (in module numpy.ma), 188, 303, 880 mod (in module numpy), 759
masked_outside() (in module numpy.ma), 189, 304, 881 mod() (in module numpy.core.defchararray), 962
masked_print_options (in module numpy.ma), 198 modf (in module numpy), 759
masked_values() (in module numpy.ma), 189, 305, 882 mr_ (in module numpy.ma), 278, 856
masked_where() (in module numpy.ma), 191, 306, 883 msort() (in module numpy), 660
MaskedArray (class in numpy.ma), 198 multinomial() (in module numpy.random), 586
MaskType (in module numpy.ma), 244, 822 multinomial() (numpy.random.mtrand.RandomState
mat() (in module numpy), 419 method), 625
matrix, 97 multiply (in module numpy), 754
matrix (class in numpy), 98 multiply() (in module numpy.core.defchararray), 961
matrix_power() (in module numpy.linalg), 543 multivariate_normal() (in module numpy.random), 587
max (numpy.iinfo attribute), 488 multivariate_normal() (numpy.random.mtrand.RandomState
max() (in module numpy.ma), 339, 916 method), 626
max() (numpy.generic method), 74
max() (numpy.ma.MaskedArray method), 227, 341, 918 N
max() (numpy.matrix method), 109 name (C member), 1022
max() (numpy.ndarray method), 19 name (numpy.dtype attribute), 87
max() (numpy.recarray method), 157 names (numpy.dtype attribute), 89
max() (numpy.record method), 171 nan_to_num() (in module numpy), 769
maximum (in module numpy), 768 nanargmax() (in module numpy), 662
maximum_fill_value() (in module numpy.ma), 315, 316, nanargmin() (in module numpy), 662
892, 893 nanmax() (in module numpy), 694
mean (in module numpy.ma), 324, 901 nanmin() (in module numpy), 695
mean() (in module numpy), 698 nansum() (in module numpy), 734
mean() (numpy.generic method), 74 nargs (C member), 1021
mean() (numpy.ma.MaskedArray method), 228, 332, 909 nargs (numpy.ufunc attribute), 378
mean() (numpy.matrix method), 110 nbytes (numpy.ma.MaskedArray attribute), 203
mean() (numpy.ndarray method), 20, 58 nbytes (numpy.ndarray attribute), 9, 34
mean() (numpy.recarray method), 157 nd (C member), 1014, 1024, 1026
mean() (numpy.record method), 171 nd_m1 (C member), 1023
median() (in module numpy), 699 ndarray, 96
median() (in module numpy.ma), 325, 902 C-API, 1032, 1064
memmap (class in numpy), 124, 506 memory model, 1075
memory maps, 124 special methods getslice, 92
memory model special methods setslice, 92
ndarray, 1075 view, 93
meshgrid() (in module numpy), 413 ndarray (class in numpy), 4
methods ndenumerate (class in numpy), 178, 479
accumulate, ufunc, 1081 ndim (numpy.generic attribute), 68
reduce, ufunc, 1081 ndim (numpy.ma.MaskedArray attribute), 203
reduceat, ufunc, 1081 ndim (numpy.ndarray attribute), 9, 33
ufunc, 380 ndincr() (numpy.ndindex method), 480
mgrid (in module numpy), 414 ndindex (class in numpy), 479
min (numpy.iinfo attribute), 488 ndpointer() (in module numpy.ctypeslib), 959
min() (in module numpy.ma), 339, 916 negative (in module numpy), 753
min() (numpy.generic method), 74 negative_binomial() (in module numpy.random), 588
min() (numpy.ma.MaskedArray method), 229, 341, 918 negative_binomial() (numpy.random.mtrand.RandomState
min() (numpy.matrix method), 110 method), 627
min() (numpy.ndarray method), 20, 56 newaxis, 92
min() (numpy.recarray method), 157 newaxis (in module numpy), 93
Index 1107
NumPy Reference, Release 2.0.0.dev8464
1108 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1109
NumPy Reference, Release 2.0.0.dev8464
1110 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1111
NumPy Reference, Release 2.0.0.dev8464
1112 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1113
NumPy Reference, Release 2.0.0.dev8464
1114 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1115
NumPy Reference, Release 2.0.0.dev8464
1116 Index
NumPy Reference, Release 2.0.0.dev8464
Index 1117
NumPy Reference, Release 2.0.0.dev8464
Y
yellow_text() (in module numpy.distutils.misc_util), 1000
Z
zeros (in module numpy.ma), 251, 829
zeros() (in module numpy), 392
zeros_like() (in module numpy), 393
zfill() (in module numpy.core.defchararray), 970
zfill() (numpy.chararray method), 146
zfill() (numpy.core.defchararray.chararray method), 996
zipf() (in module numpy.random), 607
zipf() (numpy.random.mtrand.RandomState method), 652
1118 Index