You are on page 1of 1482

NumPy Reference

Release 1.8.1

Written by the NumPy community

March 26, 2014

CONTENTS

1

2

3

Array objects
1.1 The N-dimensional array (ndarray)
1.2 Scalars . . . . . . . . . . . . . . . .
1.3 Data type objects (dtype) . . . . . .
1.4 Indexing . . . . . . . . . . . . . . .
1.5 Iterating Over Arrays . . . . . . . . .
1.6 Standard array subclasses . . . . . .
1.7 Masked arrays . . . . . . . . . . . .
1.8 The Array Interface . . . . . . . . .
1.9 Datetimes and Timedeltas . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

3
3
71
87
102
107
118
233
418
423

Universal functions (ufunc)
2.1 Broadcasting . . . . . . .
2.2 Output type determination
2.3 Use of internal buffers . .
2.4 Error handling . . . . . .
2.5 Casting Rules . . . . . . .
2.6 ufunc . . . . . . . . . .
2.7 Available ufuncs . . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

431
431
432
432
432
435
437
446

Routines
3.1 Array creation routines . . . . . . . . . . . . . . . . . . . . . . .
3.2 Array manipulation routines . . . . . . . . . . . . . . . . . . . .
3.3 Binary operations . . . . . . . . . . . . . . . . . . . . . . . . . .
3.4 String operations . . . . . . . . . . . . . . . . . . . . . . . . . .
3.5 C-Types Foreign Function Interface (numpy.ctypeslib) . . .
3.6 Datetime Support Functions . . . . . . . . . . . . . . . . . . . .
3.7 Data type routines . . . . . . . . . . . . . . . . . . . . . . . . .
3.8 Optionally Scipy-accelerated routines (numpy.dual) . . . . . .
3.9 Mathematical functions with automatic domain (numpy.emath)
3.10 Floating point error handling . . . . . . . . . . . . . . . . . . . .
3.11 Discrete Fourier Transform (numpy.fft) . . . . . . . . . . . .
3.12 Financial functions . . . . . . . . . . . . . . . . . . . . . . . . .
3.13 Functional programming . . . . . . . . . . . . . . . . . . . . . .
3.14 Numpy-specific help functions . . . . . . . . . . . . . . . . . . .
3.15 Indexing routines . . . . . . . . . . . . . . . . . . . . . . . . . .
3.16 Input and output . . . . . . . . . . . . . . . . . . . . . . . . . .
3.17 Linear algebra (numpy.linalg) . . . . . . . . . . . . . . . .
3.18 Logic functions . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

451
451
484
524
531
576
577
582
600
601
601
608
630
640
645
648
680
703
736

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

i

3.19
3.20
3.21
3.22
3.23
3.24
3.25
3.26
3.27
3.28
3.29
3.30
3.31
3.32
3.33

Masked array operations . . . . . . . . . . . . . . .
Mathematical functions . . . . . . . . . . . . . . .
Matrix library (numpy.matlib) . . . . . . . . . .
Numarray compatibility (numpy.numarray) . . .
Old Numeric compatibility (numpy.oldnumeric)
Miscellaneous routines . . . . . . . . . . . . . . . .
Padding Arrays . . . . . . . . . . . . . . . . . . . .
Polynomials . . . . . . . . . . . . . . . . . . . . .
Random sampling (numpy.random) . . . . . . .
Set routines . . . . . . . . . . . . . . . . . . . . . .
Sorting, searching, and counting . . . . . . . . . . .
Statistics . . . . . . . . . . . . . . . . . . . . . . .
Test Support (numpy.testing) . . . . . . . . . .
Asserts . . . . . . . . . . . . . . . . . . . . . . . .
Window functions . . . . . . . . . . . . . . . . . .

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

754
875
939
945
945
945
946
950
1131
1234
1239
1255
1283
1284
1296

4

Packaging (numpy.distutils)
1305
4.1 Modules in numpy.distutils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1305
4.2 Building Installable C libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1316
4.3 Conversion of .src files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1317

5

Numpy C-API
5.1 Python Types and C-Structures . .
5.2 System configuration . . . . . . . .
5.3 Data Type API . . . . . . . . . . .
5.4 Array API . . . . . . . . . . . . .
5.5 Array Iterator API . . . . . . . . .
5.6 UFunc API . . . . . . . . . . . . .
5.7 Generalized Universal Function API
5.8 Numpy core libraries . . . . . . . .
5.9 C API Deprecations . . . . . . . .

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.

1319
1319
1333
1335
1340
1379
1395
1401
1404
1408

6

Numpy internals
1411
6.1 Numpy C Code Explanations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1411
6.2 Internal organization of numpy arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1418
6.3 Multidimensional Array Indexing Order Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1419

7

Numpy and SWIG
1421
7.1 Numpy.i: a SWIG Interface File for NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1421
7.2 Testing the numpy.i Typemaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1436

8

Acknowledgements

1439

Bibliography

1441

Index

1449

ii

NumPy Reference, Release 1.8.1

Release
1.8
Date
March 26, 2014
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 user.

CONTENTS

1

NumPy Reference, Release 1.8.1

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

1.1 The N-dimensional array (ndarray)
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.
3

NumPy Reference, Release 1.8.1

Different 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:
>>> x = np.array([[1, 2, 3], [4, 5, 6]], np.int32)
>>> type(x)
<type ’numpy.ndarray’>
>>> x.shape
(2, 3)
>>> x.dtype
dtype(’int32’)

The array can be indexed using Python container-like syntax:
>>> x[1,2] # i.e., the element of x in the *second* row, *third*
column, namely, 6.

For example slicing can produce views of the array:
>>> 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]])

1.1.1 Constructing arrays
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 numpy.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.
4

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

dtype : data-type, optional
Any object that can be interpreted as a numpy data type.
buffer : object exposing buffer interface, optional
Used to fill the array with data.
offset : int, optional
Offset of array data in buffer.
strides : tuple of ints, optional
Strides of data in memory.
order : {‘C’, ‘F’}, optional
Row-major or column-major order.
See Also:
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:
>>> np.ndarray(shape=(2,2), dtype=float, order=’F’)
array([[ -1.13698227e+002,
4.25087011e-303],
[ 2.88528414e-306,
3.27025015e-309]])

#random

Second mode:
>>> np.ndarray((2,), buffer=np.array([1,2,3]),
...
offset=np.int_().itemsize,
...
dtype=int) # offset = 1*itemsize, i.e. skip first element
array([2, 3])

Attributes

1.1. The N-dimensional array (ndarray)

5

NumPy Reference, Release 1.8.1

T
data
dtype
flags
flat
imag
real
size
itemsize
nbytes
ndim
shape
strides
ctypes
base

Same as self.transpose(), except that self is returned if self.ndim < 2.
Python buffer object pointing to the start of the array’s data.
Data-type of the array’s elements.
Information about the memory layout of the array.
A 1-D iterator over the array.
The imaginary part of the array.
The real part of the array.
Number of elements in the array.
Length of one array element in bytes.
Total bytes consumed by the elements of the array.
Number of array dimensions.
Tuple of array dimensions.
Tuple of bytes to step in each dimension when traversing an array.
An object to simplify the interaction of the array with the ctypes module.
Base object if memory is from some other object.

ndarray.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.])

ndarray.data
Python buffer object pointing to the start of the array’s data.
ndarray.dtype
Data-type of the array’s elements.
Parameters
None
Returns
d : numpy dtype object
See Also:
numpy.dtype
Examples
>>> x
array([[0, 1],
[2, 3]])
>>> x.dtype
dtype(’int32’)

6

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> type(x.dtype)
<type ’numpy.dtype’>

ndarray.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
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.
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional
arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that
self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0]
== self.itemsize for Fortran-style contiguous arrays is true.

1.1. The N-dimensional array (ndarray)

7

NumPy Reference, Release 1.8.1

Attributes
C_CONTIGUOUS
The data is in a single, C-style contiguous segment.
(C)
F_CONTIGUOUS
The data is in a single, Fortran-style contiguous segment.
(F)
OWNThe array owns the memory it uses or borrows it from another object.
DATA
(O)
WRITEThe data area can be written to. Setting this to False locks the data, making it read-only.
ABLE
A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a
(W)
view of a writeable array may be subsequently locked while the base array remains
writeable. (The opposite is not true, in that a view of a locked array may not be made
writeable. However, currently, locking a base object does not lock any views that
already reference it, so under that circumstance it is possible to alter the contents of a
locked array via a previously created writeable view onto it.) Attempting to change a
non-writeable array raises a RuntimeError exception.
ALIGNED
The data and all elements are aligned appropriately for the hardware.
(A)
UPThis array is a copy of some other array. When this array is deallocated, the base array
DATEIFwill be updated with the contents of this array.
COPY
(U)
FNC
F_CONTIGUOUS and not C_CONTIGUOUS.
FORC
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
BEHAVED ALIGNED and WRITEABLE.
(B)
CARRAY
BEHAVED and C_CONTIGUOUS.
(CA)
FARRAY
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
(FA)
ndarray.flat
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in
iterator object.
See Also:
flatten
Return a copy of the array collapsed into one dimension.
flatiter
Examples
>>> x = np.arange(1, 7).reshape(2, 3)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x.flat[3]
4
>>> x.T
array([[1, 4],
[2, 5],
[3, 6]])

8

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> x.T.flat[3]
5
>>> type(x.flat)
<type ’numpy.flatiter’>

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]])

ndarray.imag
The imaginary part of the array.
Examples
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.imag
array([ 0.
, 0.70710678])
>>> x.imag.dtype
dtype(’float64’)

ndarray.real
The real part of the array.
See Also:
numpy.real
equivalent function
Examples
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.real
array([ 1.
, 0.70710678])
>>> x.real.dtype
dtype(’float64’)

ndarray.size
Number of elements in the array.
Equivalent to np.prod(a.shape), i.e., the product of the array’s dimensions.
Examples
>>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
>>> np.prod(x.shape)
30

ndarray.itemsize
Length of one array element in bytes.

1.1. The N-dimensional array (ndarray)

9

NumPy Reference, Release 1.8.1

Examples
>>>
>>>
8
>>>
>>>
16

x = np.array([1,2,3], dtype=np.float64)
x.itemsize
x = np.array([1,2,3], dtype=np.complex128)
x.itemsize

ndarray.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
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480

ndarray.ndim
Number of array dimensions.
Examples
>>>
>>>
1
>>>
>>>
3

x = np.array([1, 2, 3])
x.ndim
y = np.zeros((2, 3, 4))
y.ndim

ndarray.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
>>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
>>> y = np.zeros((2, 3, 4))
>>> y.shape
(2, 3, 4)
>>> y.shape = (3, 8)
>>> y
array([[ 0., 0., 0., 0., 0., 0.,
[ 0., 0., 0., 0., 0., 0.,
[ 0., 0., 0., 0., 0., 0.,
>>> y.shape = (3, 6)
Traceback (most recent call last):

10

0.,
0.,
0.,

0.],
0.],
0.]])

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

File "<stdin>", line 1, in <module>
ValueError: total size of new array must be unchanged

ndarray.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:
offset = sum(np.array(i) * a.strides)

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
>>> y = np.reshape(np.arange(2*3*4), (2,3,4))
>>> y
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]]])
>>> y.strides
(48, 16, 4)
>>> y[1,1,1]
17
>>> offset=sum(y.strides * np.array((1,1,1)))
>>> offset/y.itemsize
17
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3,5,2,2])
>>> offset = sum(i * x.strides)
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813

ndarray.ctypes
An object to simplify the interaction of the array with the ctypes module.

1.1. The N-dimensional array (ndarray)

11

NumPy Reference, Release 1.8.1

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.
self.shape_as(ctypes.c_short).

For example:

•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
>>> import ctypes
>>> x

12

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

array([[0, 1],
[2, 3]])
>>> x.ctypes.data
30439712
>>> 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>

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

Slicing creates a view, whose memory is shared with x:
>>> y = x[2:]
>>> y.base is x
True

Methods
all([axis, out])
any([axis, out])
argmax([axis, out])
argmin([axis, out])
argpartition(kth[, axis, kind, order])
argsort([axis, kind, order])
astype(dtype[, order, casting, subok, copy])
byteswap(inplace)
choose(choices[, out, mode])
clip(a_min, a_max[, out])
compress(condition[, axis, out])
conj()
conjugate()
copy([order])
cumprod([axis, dtype, out])
cumsum([axis, dtype, out])
diagonal([offset, axis1, axis2])

Returns True if all elements evaluate to True.
Returns True if any of the elements of a evaluate to True.
Return indices of the maximum values along the given axis.
Return indices of the minimum values along the given axis of a.
Returns the indices that would partition this array.
Returns the indices that would sort this array.
Copy of the array, cast to a specified type.
Swap the bytes of the array elements
Use an index array to construct a new array from a set of choices.
Return an array whose values are limited to [a_min, a_max].
Return selected slices of this array along given axis.
Complex-conjugate all elements.
Return the complex conjugate, element-wise.
Return a copy of the array.
Return the cumulative product of the elements along the given axis.
Return the cumulative sum of the elements along the given axis.
Return specified diagonals.

1.1. The N-dimensional array (ndarray)

13

NumPy Reference, Release 1.8.1

dot(b[, out])
dump(file)
dumps()
fill(value)
flatten([order])
getfield(dtype[, offset])
item(*args)
itemset(*args)
max([axis, out])
mean([axis, dtype, out])
min([axis, out])
newbyteorder([new_order])
nonzero()
partition(kth[, axis, kind, order])
prod([axis, dtype, out])
ptp([axis, out])
put(indices, values[, mode])
ravel([order])
repeat(repeats[, axis])
reshape(shape[, order])
resize(new_shape[, refcheck])
round([decimals, out])
searchsorted(v[, side, sorter])
setfield(val, dtype[, offset])
setflags([write, align, uic])
sort([axis, kind, order])
squeeze([axis])
std([axis, dtype, out, ddof])
sum([axis, dtype, out])
swapaxes(axis1, axis2)
take(indices[, axis, out, mode])
tofile(fid[, sep, format])
tolist()
tostring([order])
trace([offset, axis1, axis2, dtype, out])
transpose(*axes)
var([axis, dtype, out, ddof])
view([dtype, type])

Table 1.3 – continued from previous page
Dot product of two arrays.
Dump a pickle of the array to the specified file.
Returns the pickle of the array as a string.
Fill the array with a scalar value.
Return a copy of the array collapsed into one dimension.
Returns a field of the given array as a certain type.
Copy an element of an array to a standard Python scalar and return it.
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
Return the maximum along a given axis.
Returns the average of the array elements along given axis.
Return the minimum along a given axis.
Return the array with the same data viewed with a different byte order.
Return the indices of the elements that are non-zero.
Rearranges the elements in the array in such a way that value of the element in kth po
Return the product of the array elements over the given axis
Peak to peak (maximum - minimum) value along a given axis.
Set a.flat[n] = values[n] for all n in indices.
Return a flattened array.
Repeat elements of an array.
Returns an array containing the same data with a new shape.
Change shape and size of array in-place.
Return a with each element rounded to the given number of decimals.
Find indices where elements of v should be inserted in a to maintain order.
Put a value into a specified place in a field defined by a data-type.
Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively.
Sort an array, in-place.
Remove single-dimensional entries from the shape of a.
Returns the standard deviation of the array elements along given axis.
Return the sum of the array elements over the given axis.
Return a view of the array with axis1 and axis2 interchanged.
Return an array formed from the elements of a at the given indices.
Write array to a file as text or binary (default).
Return the array as a (possibly nested) list.
Construct a Python string containing the raw data bytes in the array.
Return the sum along diagonals of the array.
Returns a view of the array with axes transposed.
Returns the variance of the array elements, along given axis.
New view of array with the same data.

ndarray.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
ndarray.any(axis=None, out=None)
Returns True if any of the elements of a evaluate to True.
Refer to numpy.any for full documentation.
14

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

See Also:
numpy.any
equivalent function
ndarray.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
ndarray.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
ndarray.argpartition(kth, axis=-1, kind=’introselect’, order=None)
Returns the indices that would partition this array.
Refer to numpy.argpartition for full documentation. New in version 1.8.0.
See Also:
numpy.argpartition
equivalent function
ndarray.argsort(axis=-1, kind=’quicksort’, order=None)
Returns the indices that would sort this array.
Refer to numpy.argsort for full documentation.
See Also:
numpy.argsort
equivalent function
ndarray.astype(dtype, order=’K’, casting=’unsafe’, subok=True, copy=True)
Copy of the array, cast to a specified type.
Parameters
dtype : str or dtype
Typecode or data-type to which the array is cast.
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran
order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise,
and ‘K’ means as close to the order the array elements appear in memory as possible.
Default is ‘K’.

1.1. The N-dimensional array (ndarray)

15

NumPy Reference, Release 1.8.1

casting : {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
• ‘no’ means the data types should not be cast at all.
• ‘equiv’ means only byte-order changes are allowed.
• ‘safe’ means only casts which can preserve values are allowed.
• ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are
allowed.
• ‘unsafe’ means any data conversions may be done.
subok : bool, optional
If True, then sub-classes will be passed-through (default), otherwise the returned array
will be forced to be a base-class array.
copy : bool, optional
By default, astype always returns a newly allocated array. If this is set to false, and the
dtype, order, and subok requirements are satisfied, the input array is returned instead
of a copy.
Returns
arr_t : ndarray
Unless copy is False and the other conditions for returning the input array are satisfied
(see description for copy input paramter), arr_t is a new array of the same shape as the
input array, with dtype, order given by dtype, order.
Raises
ComplexWarning
When casting from complex to float or int.
a.real.astype(t).

To avoid this, one should use

Examples
>>> x = np.array([1, 2, 2.5])
>>> x
array([ 1. , 2. , 2.5])
>>> x.astype(int)
array([1, 2, 2])

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

16

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

Examples
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> map(hex, A)
[’0x1’, ’0x100’, ’0x2233’]
>>> A.byteswap(True)
array([ 256,
1, 13090], dtype=int16)
>>> map(hex, A)
[’0x100’, ’0x1’, ’0x3322’]

Arrays of strings are not swapped
>>> A = np.array([’ceg’, ’fac’])
>>> A.byteswap()
array([’ceg’, ’fac’],
dtype=’|S3’)

ndarray.choose(choices, out=None, mode=’raise’)
Use an index array to construct a new array from a set of choices.
Refer to numpy.choose for full documentation.
See Also:
numpy.choose
equivalent function
ndarray.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
ndarray.compress(condition, axis=None, out=None)
Return selected slices of this array along given axis.
Refer to numpy.compress for full documentation.
See Also:
numpy.compress
equivalent function
ndarray.conj()
Complex-conjugate all elements.
Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
ndarray.conjugate()
Return the complex conjugate, element-wise.

1.1. The N-dimensional array (ndarray)

17

NumPy Reference, Release 1.8.1

Refer to numpy.conjugate for full documentation.
See Also:
numpy.conjugate
equivalent function
ndarray.copy(order=’C’)
Return a copy of the array.
Parameters
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’
means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as
closely as possible. (Note that this function and :func:numpy.copy are very similar, but
have different default values for their order= arguments.)
See Also:
numpy.copy, numpy.copyto
Examples
>>> x = np.array([[1,2,3],[4,5,6]], order=’F’)
>>> 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

ndarray.cumprod(axis=None, dtype=None, out=None)
Return the cumulative product of the elements along the given axis.
Refer to numpy.cumprod for full documentation.
See Also:
numpy.cumprod
equivalent function
ndarray.cumsum(axis=None, dtype=None, out=None)
Return the cumulative sum of the elements along the given axis.
Refer to numpy.cumsum for full documentation.
See Also:
numpy.cumsum
equivalent function

18

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

ndarray.diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals.
Refer to numpy.diagonal for full documentation.
See Also:
numpy.diagonal
equivalent function
ndarray.dot(b, out=None)
Dot product of two arrays.
Refer to numpy.dot for full documentation.
See Also:
numpy.dot
equivalent function
Examples
>>> a = np.eye(2)
>>> b = np.ones((2, 2)) * 2
>>> a.dot(b)
array([[ 2., 2.],
[ 2., 2.]])

This array method can be conveniently chained:
>>> a.dot(b).dot(b)
array([[ 8., 8.],
[ 8., 8.]])

ndarray.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.
ndarray.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
ndarray.fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples

1.1. The N-dimensional array (ndarray)

19

NumPy Reference, Release 1.8.1

>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([ 1., 1.])

ndarray.flatten(order=’C’)
Return a copy of the array collapsed into one dimension.
Parameters
order : {‘C’, ‘F’, ‘A’}, optional
Whether to flatten in C (row-major), Fortran (column-major) order, or preserve the
C/Fortran ordering from a. 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
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten(’F’)
array([1, 3, 2, 4])

ndarray.getfield(dtype, offset=0)
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the
given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits
in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with
a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
Parameters
dtype : str or dtype
The data type of the view. The dtype size of the view can not be larger than that of the
array itself.
offset : int
Number of bytes to skip before beginning the element view.
Examples

20

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> x = np.diag([1.+1.j]*2)
>>> x[1, 1] = 2 + 4.j
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 2.+4.j]])
>>> x.getfield(np.float64)
array([[ 1., 0.],
[ 0., 2.]])

By choosing an offset of 8 bytes we can select the complex part of the array for our view:
>>> x.getfield(np.float64, offset=8)
array([[ 1., 0.],
[ 0., 4.]])

ndarray.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 Python’s optimized math.
Examples
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[3, 1, 7],
[2, 8, 3],
[8, 5, 3]])
>>> x.item(3)
2
>>> x.item(7)
5
>>> x.item((0, 1))
1
>>> x.item((2, 2))
3

1.1. The N-dimensional array (ndarray)

21

NumPy Reference, Release 1.8.1

ndarray.itemset(*args)
Insert scalar into an array (scalar is cast to array’s dtype, if possible)
There must be at least 1 argument, and define the last argument as item. Then, a.itemset(*args) is
equivalent to but faster than a[args] = item. The item should be a scalar value and args must select
a single item in the array a.
Parameters
*args : Arguments
If one argument: a scalar, only used in case a is of size 1. If two arguments: the last
argument is the value to be set and must be a scalar, the first argument specifies a single
array element location. It is either an int or a tuple.
Notes
Compared to indexing syntax, itemset provides some speed increase for placing a scalar into a particular
location in an ndarray, if you must do this. However, generally this is discouraged: among other
problems, it complicates the appearance of the code. Also, when using itemset (and item) inside a
loop, be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.
Examples
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[3, 1, 7],
[2, 8, 3],
[8, 5, 3]])
>>> x.itemset(4, 0)
>>> x.itemset((2, 2), 9)
>>> x
array([[3, 1, 7],
[2, 0, 3],
[8, 5, 9]])

ndarray.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
ndarray.mean(axis=None, dtype=None, out=None)
Returns the average of the array elements along given axis.
Refer to numpy.mean for full documentation.
See Also:
numpy.mean
equivalent function
ndarray.min(axis=None, out=None)
Return the minimum along a given axis.
Refer to numpy.amin for full documentation.
See Also:
22

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

numpy.amin
equivalent function
ndarray.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:
*
*
*
*
*

’S’ {’<’,
{’>’,
{’=’,
{’|’,

swap
’L’}
’B’}
’N’}
’I’}

dtype from current to opposite endian
- little endian
- big endian
- native order
- ignore (no change to byte order)

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.
ndarray.nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
ndarray.partition(kth, axis=-1, kind=’introselect’, order=None)
Rearranges the elements in the array in such a way that value of the element in kth position is in the
position it would be in a sorted array. All elements smaller than the kth element are moved before this
element and all equal or greater are moved behind it. The ordering of the elements in the two partitions is
undefined. New in version 1.8.0.
Parameters
kth : int or sequence of ints
Element index to partition by. The kth element value will be in its final sorted position
and all smaller elements will be moved before it and all equal or greater elements behind
it. The order all elements in the partitions is undefined. If provided with a sequence of
kth it will partition all elements indexed by kth of them into their sorted position at once.
axis : int, optional
Axis along which to sort. Default is -1, which means sort along the last axis.

1.1. The N-dimensional array (ndarray)

23

NumPy Reference, Release 1.8.1

kind : {‘introselect’}, optional
Selection algorithm. Default is ‘introselect’.
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.partition
Return a parititioned copy of an array.
argpartition
Indirect partition.
sort
Full sort.
Notes
See np.partition for notes on the different algorithms.
Examples
>>> a = np.array([3, 4, 2, 1])
>>> a.partition(a, 3)
>>> a
array([2, 1, 3, 4])
>>> a.partition((1, 3))
array([1, 2, 3, 4])

ndarray.prod(axis=None, dtype=None, out=None)
Return the product of the array elements over the given axis
Refer to numpy.prod for full documentation.
See Also:
numpy.prod
equivalent function
ndarray.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
ndarray.put(indices, values, mode=’raise’)
Set a.flat[n] = values[n] for all n in indices.
Refer to numpy.put for full documentation.
See Also:

24

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

numpy.put
equivalent function
ndarray.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.
ndarray.repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function
ndarray.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
ndarray.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:

1.1. The N-dimensional array (ndarray)

25

. [2.resize((1. order=’C’) >>> a. and reshaped: >>> a = np. 1). However. out=None) Return a with each element rounded to the given number of decimals. >>> c = a >>> a.array([[0. Release 1.round(decimals=0. refcheck=False) >>> a array([[0]]) >>> c array([[0]]) ndarray. 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..resize((2.resize((2.. 2]... [2.resize(2. 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. [2]]) Enlarging an array: as above. [1]]) >>> a = np. [2. Refer to numpy. Array objects .around for full documentation. See Also: 26 Chapter 1. 1].. resized. Only contiguous arrays (data elements consecutive in memory) can be resized. 1)) Traceback (most recent call last): . 3]]) >>> b.resize((1. Notes This reallocates space for the data area if necessary. 1)) >>> a array([[0]. 1. 1].array([[0. 0]]) Referencing an array prevents resizing.NumPy Reference. 0. but missing entries are filled with zeros: >>> b = np. Unless refcheck is False: >>> a. 3]]. then you may safely set refcheck to False. 1]. ValueError: cannot resize an array that has been referenced . 3]].8. 1)) >>> a array([[0].array([[0. 3) # new_shape parameter doesn’t have to be a tuple >>> b array([[0. [3.1 resize Return a new array with the specified shape. order=’F’) >>> a. Examples Shrinking an array: array is flattened (in the order that the data are stored in memory).

searchsorted(v.int32) array([[3. [ 0. uic=None) Set array flags WRITEABLE.. ALIGNED. [3. [ 0.00000000e+000. dtype : dtype object Data-type of the field in which to place val.NumPy Reference. 3]. For full documentation.00000000e+000.around equivalent function ndarray. 1.48219694e-323.1 numpy. 1. 3]. [ 1. 0. 0.]]) 1.int32) >>> x array([[ 1..setfield(val..eye(3). 0.setfield(np.float64) array([[ 1.8. 3. 1. 1.]. and UPDATEIFCOPY. sorter=None) Find indices where elements of v should be inserted in a to maintain order. offset : int. 3. 1. Parameters val : object Value to be placed in field. >>> x. [3.searchsorted See Also: numpy..]. offset=0) Put a value into a specified place in a field defined by a data-type. [ 0.]]) >>> x.. see numpy. 3. align=None. respectively..... np. dtype.48219694e-323.getfield(np.int32) >>> x. Returns None See Also: getfield Examples >>> x = np. 0. The N-dimensional array (ndarray) 27 . 1. np. 1. 1. 0.1. 3]]) >>> x array([[ 1.setfield(3.searchsorted equivalent function ndarray. 0.eye(3) >>> x. optional The number of bytes into the field at which to place val. [ 1. 0. 1. [ 0.].48219694e-323]. side=’left’.. Release 1. 0.].00000000e+000]]) ndarray. Place val into a‘s field defined by dtype and beginning offset bytes into the field.getfield(np.48219694e-323]..48219694e-323.. 1.setflags(write=None.48219694e-323.

[8. There are 6 Boolean flags in use. 9]]) >>> y. optional Describes whether or not a is a copy of another “base” array. optional Describes whether or not a is aligned properly for its type. 0. or is a string. the base array will be updated with the contents of this array.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False UPDATEIFCOPY : False >>> y. WRITEABLE (W) the data area can be written to. Examples >>> y array([[3. Release 1. Array objects . 1. uic : bool. and ALIGNED.8. The ALIGNED flag can only be set to True if the data is actually aligned according to the type.NumPy Reference. The flag WRITEABLE can only be set to True if the array owns its own memory. The UPDATEIFCOPY flag can never be set to True. align : bool.) Parameters write : bool. 5.base).flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y. 0]. All flags can be accessed using their first (upper case) letter as well as the full name. [2. (The exception for string is made so that unpickling can be done without copying memory. UPDATEIFCOPY (U) this array is a copy of some other array (referenced by . only three of which can be changed by the user: UPDATEIFCOPY. line 1. optional Describes whether or not a can be written to. 7].setflags(uic=1) Traceback (most recent call last): File "<stdin>". WRITEABLE. When this array is deallocated.setflags(write=0. align=0) >>> y. or the ultimate owner of the memory exposes a writeable buffer interface.1 These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler). Notes Array flags provide information about how the memory area used for the array is to be interpreted. in <module> ValueError: cannot set UPDATEIFCOPY flag to True 28 Chapter 1.

See Also: numpy.sort(order=’y’) >>> a array([(’c’.1 ndarray.8. int)]) >>> a.sort(axis=1) >>> a array([[1. [3.4]. kind : {‘quicksort’. The N-dimensional array (ndarray) 29 .squeeze(axis=None) Remove single-dimensional entries from the shape of a. Refer to numpy. [1. second. ’<i4’)]) ndarray. partition Partial sort. in-place.sort(axis=-1.sort Return a sorted copy of an array. (’c’. argsort Indirect sort. 2)]. (’a’. 3]]) >>> a. 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> a = np. etc. 2).NumPy Reference.squeeze for full documentation. [1. Examples >>> a = np. Default is -1. kind=’quicksort’. 1). this argument specifies which fields to compare first. 1. optional Axis along which to sort. 4]. optional Sorting algorithm. Parameters axis : int. ‘heapsort’}.array([[1. ’|S1’). order : list.sort(axis=0) >>> a array([[1.1]]) >>> a. Notes See sort for notes on the different sorting algorithms. optional When a is an array with fields defined.array([(’a’. Release 1. ‘mergesort’. which means sort along the last axis. 1)]. 3]. dtype=[(’x’. Not all fields need be specified. dtype=[(’x’. Default is ‘quicksort’.1. order=None) Sort an array. (’y’. searchsorted Find elements in sorted array. lexsort Indirect stable sort on multiple keys. (’y’. ’S1’).

mode=’raise’) Return an array formed from the elements of a at the given indices. Refer to numpy. See Also: numpy. See Also: numpy. Refer to numpy. dtype=None.sum for full documentation. out=None) Return the sum of the array elements over the given axis.std(axis=None.take equivalent function ndarray. See Also: numpy. a binary file is written. dtype=None. Array objects .NumPy Reference.swapaxes(axis1. Data is always written in ‘C’ order.sum equivalent function ndarray. Parameters fid : file or str An open file object.tostring()). ddof=0) Returns the standard deviation of the array elements along given axis. independent of the order of a. sep : str Separator between array items for text output.std for full documentation.swapaxes equivalent function ndarray.squeeze equivalent function ndarray.8.sum(axis=None.write(a. The data produced by this method can be recovered using the function fromfile(). Release 1. equivalent to file.take for full documentation. axis=None.take(indices.1 See Also: numpy. format=”%s”) Write array to a file as text or binary (default). sep=”“. Refer to numpy.swapaxes for full documentation. See Also: numpy.std equivalent function ndarray. Refer to numpy. 30 Chapter 1. If “” (empty). out=None. or a string containing a filename. out=None. axis2) Return a view of the array with axis1 and axis2 interchanged.tofile(fid.

at the expense of speed and file size. Examples >>> a = np.array([[1. ndarray. 4]]) >>> list(a) [array([1. The string can be produced in either ‘C’ or ‘Fortran’. [3. 2]. Return a copy of the array data as a (nested) Python list. or ‘Any’ order (the default is ‘C’-order). and then using “format” % item. a = np. so this method is not a good choice for files intended to archive data or transport data between machines with different endianness.1. The N-dimensional array (ndarray) 31 . array([3. 2]) >>> a. 4])] >>> a. Fortran. ‘Any’ order means C-order unless the F_CONTIGUOUS flag in the array is set.array(a.tolist() [[1. Notes The array may be recreated.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.tolist() Return the array as a (possibly nested) list.tolist() [1. None}. 4]] ndarray. Some of these problems can be overcome by outputting the data as text files. Parameters order : {‘C’. Information on endianness and precision is lost. Each entry in the array is formatted to text by first converting it to the closest Python type.1 format : str Format string for text file output. optional Order of the data for multidimensional arrays: C.array([1. in which case it means ‘Fortran’ order. [3. 2]). Data items are converted to the nearest compatible Python type. Parameters none Returns y : list The possibly nested list of array elements.8. ‘F’. 2]. Release 1.tolist()).NumPy Reference. 2] >>> a = np. 1. or the same as for the original array. Returns s : str A Python string exhibiting a copy of a‘s raw data. Notes This is a convenience function for quick storage of array data.

i[n-2].shape = (i[n-1]. i[n-2]. tuple of ints. this is the usual matrix transpose. axis1=0.. 4]]) >>> a.tostring() ’\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00’ >>> x.1 Examples >>> x = np. their order indicates how the axes are permuted (see Examples). If axes are not provided and a. 0)) array([[1. Array objects .transpose()‘s j-th axis. Examples >>> a = np. 4]]) >>> a array([[1.transpose(). dtype=None. Parameters axes : None.transpose() array([[1.shape = (i[0]. out=None) Return the sum along diagonals of the array. i[n-1]). i[1].. ..trace(offset=0.trace for full documentation.. 3].transpose((1. i[1].) For a 2-D array.array([[1. i[0]).tostring(’C’) == x. • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a.tostring(’F’) ’\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00’ ndarray. if axes are given.8. 2]. Refer to numpy.array([[0. Release 1. or n ints • None or no argument: reverses the order of the axes. (To change between column and row vectors.T Array property returning the array transposed. 2].trace equivalent function ndarray. axis2=1. this has no effect. 32 Chapter 1. .tostring() True >>> x. 4]]) >>> a.NumPy Reference. For a 1-D array. [3. See Also: numpy. • 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. [3. 3]. See Also: ndarray. first cast the 1-D array into a matrix object. with axes suitably permuted. 1]. [2. [2. For an n-D array. 3]]) >>> x.transpose(*axes) Returns a view of the array with axes transposed. then a.

Refer to numpy.g. This argument can also be specified as an ndarray sub-class.view(some_dtype) or a. np.var for full documentation. Parameters dtype : data-type or ndarray sub-class.view(some_dtype). 0) array([[1. optional Type of the returned view. out=None.defmatrix. ddof=0) Returns the variance of the array elements.var(axis=None. versus defined as a slice or transpose. dtype=None. dtype.transpose(1. float32 or int16. type=None) New view of array with the same data. optional Data-type descriptor of the returned view.int8). e. if some_dtype has a different number of bytes per entry than the previous dtype (for example.view(dtype=np.var equivalent function ndarray.NumPy Reference. converting a regular array to a structured array).matrix’> 1. 4]]) ndarray.g. dtype=[(’a’.view() is used two different ways: a. etc. 4]]) >>> a. along given axis.. Release 1. Therefore if a is C-ordered versus fortran-ordered. Examples >>> x = np. The default. type : Python type.int8)]) Viewing array data using a different type and dtype: >>> y = x. dtype=int16) >>> print type(y) <class ’numpy.8. Again.1 [2.. results in the view having the same data-type as a. e.array([(1. It also depends on exactly how a is stored in memory. np. the view may give different results. a. which then specifies the type of the returned object (this is equivalent to setting the type parameter). then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)).1. For a.matrixlib.) This does not cause a reinterpretation of the memory.matrix) >>> y matrix([[513]]. (’b’.int16. type=np. 3]..view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. This can cause a reinterpretation of the bytes of memory.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape.view(dtype=None.view(ndarray_subclass) or a. 2)]. The N-dimensional array (ndarray) 33 . etc. Notes a. the default None results in type preservation. [2. See Also: numpy. None. ndarray or matrix.

. dtype=[(’width’. 10) >>> z[0] (9.view(dtype=[(’width’. 5)]].2.1. dtype=[(’a’. Similar syntax is also used for accessing fields in a record array.a array([1]. Release 1.int16)]) Traceback (most recent call last): File "<stdin>".int16) >>> y = x[:. array[selection]. 20) (3.int8).int8). (’length’.int16). 2). 2)].1. dtype=np. np. or by some other object).: >>> x = np. (’b’.view(dtype=[(’width’.3 Internal memory layout of an ndarray An instance of class ndarray consists of a contiguous one-dimensional segment of computer memory (owned by the array. 2]. [3.view(np.2 Indexing arrays Arrays can be indexed using an extended Python slicing syntax.4)].reshape(-1. np. Array objects . 1. >>> z = y.8.NumPy Reference. combined with an indexing scheme that maps N integers into the location of an item 34 Chapter 1. (’length’. ’<i2’). np. etc. [(4.int16). 2]. 4)] Using a view to convert an array to a record array: >>> z = x. dtype=int8) Views share data: >>> x[0] = (9. in <module> ValueError: new type not compatible with array. dtype=int16) >>> y.int8)]) >>> xv = x.1] = 20 >>> print x [(1.array([[1. See Also: Array Indexing.array([(1. (’length’.copy() >>> z.(3. line 1.view(dtype=np. 3. transposes. [4. np. 4]].1 Creating a view on a structured array so it can be used in calculations >>> x = np. 0:2] >>> y array([[1.recarray) >>> z.2) >>> xv array([[1.3].[4. ’<i2’)]) 1. fortran-ordering.]) Making changes to the view changes the underlying array >>> xv[0.5.mean(0) array([ 2. dtype=int8) >>> xv. 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices. np. 5]]. np.int16)]) array([[(1.6]].

In a strided scheme. Any array with no elements may be considered C-style and Fortran-style contiguous.8. An array is considered aligned if the memory offsets for all elements and the base offset itself is a multiple of self. which has the corresponding flags set. If self.1). This also means that even a high dimensional array could be C-style and Fortran-style contiguous at the same time. srow = k N −1 Y dj . then your NumPy has relaxed strides checking enabled. Release 1. The N-dimensional array (ndarray) 35 .8. While a C-style and Fortran-style contiguous array. the N-dimensional index (n0 .NumPy Reference. a copy is automatically made. How many bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.itemsize * self. and correspond to memory that can be addressed by the strides: scolumn = k k−1 Y j=0 dj . i. some algorithms require singlesegment arrays. The column-major order (used.strides[k] is arbitrary.e. in the Fortran language and in Matlab) and row-major order (used in C) schemes are just specific kinds of strided scheme. can be addressed with the above strides. Point 1. When an irregularly strided array is passed in to such algorithms. 1. Note: Points (1) and (2) are not yet applied by default.. and there are many different schemes for arranging the items of an N-dimensional array in a 1-dimensional block. This can happen in two cases: 1.flags.ones((10.1 in the block.squeeze() always have the same contiguity and aligned flags value. 2. Warning: It does not generally hold that self.1. for example. order=’C’).itemsize for C-style contiguous arrays or self. means that self‘‘and ‘‘self. This means that in the formula for the offset nk = 0 and thus sk nk = 0 and the value of sk = self.shape[j]. in which every part of the memory block can be accessed by some combination of the indices.itemsize for Fortran-style contiguous arrays is true. The ranges in which the indices can vary is specified by the shape of the array. . n1 . If this is True.. Eventually this will become the default. However. unless otherwise specified. Data in new ndarrays is in the row-major (C) order.0. they are applied consistently only if the environment variable NPY_RELAXED_STRIDES_CHECKING=1 was defined when NumPy was built. Both the C and Fortran orders are contiguous. j=k+1 where dj = self.shape[k] == 1 then for any legal index index[k] == 0.size == 0) there is no legal index and the strides are never used. A segment of memory is inherently 1-dimensional. single-segment. Note: Several algorithms in NumPy work on arbitrarily strided arrays. the actual strides may be different. memory layouts. nN −1 ) corresponds to the offset (in bytes): noffset = N −1 X sk nk k=0 from the beginning of the memory block associated with the array. If an array has no elements (self. for example. Beginning with Numpy 1. basic array slicing often produces views in a different scheme..f_contiguous. Here. sk are integers which specify the strides of the array.strides[0] == self. and ndarray objects can accommodate any strided indexing scheme.strides[-1] == self. Numpy is flexible. You can check whether this option was enabled when your NumPy was built by looking at the value of np.itemsize. but..

or by using lowercased attribute names (as in a.nbytes ndarray.shape ndarray. Base object if memory is from some other object. It does not generally hold that self. accessing an array through its attributes allows you to get and sometimes set intrinsic properties of the array without creating a new array.1. via direct assignment to the attribute or dictionary entry. Tuple of bytes to step in each dimension when traversing an array. ndarray. Information on each attribute is given below. Only the UPDATEIFCOPY.strides[0] == self. Array objects .itemsize for Fortran-style contiguous arrays is true.itemsize ndarray.itemsize for C-style contiguous arrays or self.flags Information about the memory layout of the array.base Information about the memory layout of the array. WRITEABLE.1 1. •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.strides[dim] may be arbitrary if arr. The array flags cannot be set arbitrarily: •UPDATEIFCOPY can only be set False. Length of one array element in bytes. Python buffer object pointing to the start of the array’s data.flags.flags[’WRITEABLE’]). but can also be true for higher dimensional arrays. Number of array dimensions. This is clear for 1-dimensional arrays. or by calling ndarray.data ndarray.strides[-1] == self.strides ndarray.size ndarray. Arrays can be both C-style and Fortran-style contiguous simultaneously. and ALIGNED flags can be changed by the user. Generally. Short flag names are only supported in dictionary access. Number of elements in the array. Release 1.8.flags ndarray.shape[dim] == 1 or the array has no elements.writeable). 36 Chapter 1. Tuple of array dimensions.ndim ndarray. •ALIGNED can only be set True if the data is truly aligned. The exposed attributes are the core parts of an array and only some of them can be reset meaningfully without creating a new array. Even for contiguous arrays a stride for a given dimension arr. Memory layout The following attributes contain information about the memory layout of the array: ndarray. Notes The flags object can be accessed dictionary-like (as in a.4 Array attributes Array attributes reflect information that is intrinsic to the array itself.setflags.NumPy Reference. Total bytes consumed by the elements of the array.

etc..zeros((2. >>> y. 0.. locking a base object does not lock any views that already reference it. 6) Traceback (most recent call last): File "<stdin>". However.) inherits WRITEABLE from its base array at creation time. (C) F_CONTIGUOUS The data is in a single. (FA) ndarray. (CA) FARRAY BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. BEHAVED ALIGNED and WRITEABLE.. 0..array([1. 0. 4) >>> y.. When this array is deallocated.1.. 0..1 Attributes C_CONTIGUOUS The data is in a single. [ 0. but a view of a (W) writeable array may be subsequently locked while the base array remains writeable. 0.shape = (3. 0. 8) >>> y array([[ 0.].. 0. 3.. ALIGNED The data and all elements are aligned appropriately for the hardware. in <module> ValueError: total size of new array must be 0.shape (4. the base array will COPY be updated with the contents of this array. 0.shape Tuple of array dimensions. A ABLE view (slice. 1. Release 1.]]) unchanged ndarray. so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it. Setting this to False locks the data. 2. 0. Notes May be used to “reshape” the array. in that a view of a locked array may not be made writeable...shape (2. (O) WRITEThe data area can be written to.8. (F) OWNDATA The array owns the memory it uses or borrows it from another object. 0. currently.]. (U) FNC F_CONTIGUOUS and not C_CONTIGUOUS.. as long as this would not require a change in the total number of elements Examples >>> x = np. making it read-only. 3.. 0. 0.... 4]) >>> x. C-style contiguous segment. (The opposite is not true... 0. [ 0..shape = (3.strides Tuple of bytes to step in each dimension when traversing an array. 0. Fortran-style contiguous segment. (A) UPDATEIF.. (B) CARRAY BEHAVED and C_CONTIGUOUS. 4)) >>> y.This array is a copy of some other array. 0. 0. 0..) >>> y = np. 0. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). line 1. 0.) Attempting to change a non-writeable array raises a RuntimeError exception.NumPy Reference. 0. 3. The N-dimensional array (ndarray) 37 .

4.array(i) * a. 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.itemsize 813 ndarray. 1344) >>> i = np.3. 4).1 The byte offset of element (i[0].6.strides * np.4)) >>> y array([[[ 0. 9]]. 3]) x. 15]. 2.ndim Number of array dimensions. 224.as_strided Notes Imagine an array of 32-bit integers (each 4 bytes): x = np. 10. [5. 21.strides) >>> x[3. 7.1.array([3.1))) >>> offset/y. Examples >>> >>> 1 >>> >>> 3 38 x = np. 1.ndim y = np. one after the other (known as a contiguous block of memory).3. 4]. (2. Examples >>> y = np.rst” file in the NumPy reference guide.2. [ 8. 5. 7]. 2.int32) This array is stored in memory as 40 bytes.itemsize 17 >>> x = np.2.0) >>> x.NumPy Reference. 11]]. (5.strides) A more detailed explanation of strides can be found in the “ndarray. 6..1. 4)) y.1.7.transpose(2.2] 813 >>> offset / x. For example. dtype=np.ndim Chapter 1. 1. [20.strides (48. 18. 16.2]) >>> offset = sum(i * x..lib. but 20 bytes (5 values) to get to the same position in the next row..array([[0.strides (32. the strides for the array x will be (20.1] 17 >>> offset=sum(y. 22.reshape(np. 8. 3]. 3.5. [[12.array((1. i[1].5.array([1.arange(2*3*4).arange(5*6*7*8). 19].8)). 4) >>> y[1. 9. 13.zeros((2. [ 4. As such. Array objects . 2. 17.8. [16. 14. Release 1. we have to skip 4 bytes (1 value) to move to the next column.reshape(np. 6. 23]]]) >>> y. . See Also: numpy. i[n]) in an array a is: offset = sum(np. 3.stride_tricks.

zeros((3.itemsize Length of one array element in bytes.array([1. 5. Examples >>> x = np.2.array([1.prod(x. dtype=np. dtype=np.nbytes 480 >>> np.shape) 30 ndarray.base is None True Slicing creates a view.base is x True 1.2.data Python buffer object pointing to the start of the array’s data.size Number of elements in the array.. 2). whose memory is shared with x: >>> y = x[2:] >>> y. The N-dimensional array (ndarray) 39 . Examples >>> >>> 8 >>> >>> 16 x = np. the product of the array’s dimensions.shape). Examples >>> x = np.2).float64) x.complex128) >>> x.base Base object if memory is from some other object. dtype=np. Examples The base of an array that owns its memory is None: >>> x = np.complex128) >>> x.1. Notes Does not include memory consumed by non-element attributes of the array object. Equivalent to np.2.array([1.itemsize x = np.itemsize ndarray.NumPy Reference.zeros((3.3].3]. dtype=np.complex128) x. ndarray.3.size 30 >>> np.5. Release 1.8.shape) * x.prod(a.prod(x.itemsize 480 ndarray.nbytes Total bytes consumed by the elements of the array.1 ndarray.e. i.4]) >>> x.

dtype Examples >>> x array([[0.NumPy Reference. except that self is returned if self. except that self is returned if self. ndarray. [ 2.1 Data type See Also: Data type objects The data type object associated with the array can be found in the dtype attribute: ndarray.dtype) <type ’numpy.. [ 3.T Same as self.2..]) >>> x 40 Chapter 1.]. 1].dtype Data-type of the array’s elements.]]) >>> x. A 1-D iterator over the array.2.flat ndarray.imag ndarray. Examples >>> x = np.8..4.4.array([[1.]]) >>> x array([[ 1.. 4.array([1.].transpose().T ndarray.dtype’> Other attributes ndarray.ndim < 2.3.]]) >>> x = np. Array objects .dtype dtype(’int32’) >>> type(x.[3. ndarray. Release 1. 4. [2.].transpose()..T array([[ 1.. 2. An object to simplify the interaction of the array with the ctypes module.real ndarray. 3.dtype Data-type of the array’s elements. Parameters None Returns d : numpy dtype object See Also: numpy..ndim < 2.ctypes __array_priority__ Same as self. The real part of the array. The imaginary part of the array... 3]]) >>> x.

flat A 1-D iterator over the array. 3.. 6]]) >>> x.real The real part of the array.dtype dtype(’float64’) ndarray.real. 7). 5. 3.real equivalent function Examples >>> x = np. .T array([[1.1 array([ 1.1.real array([ 1..flat[3] 4 >>> x. 4.. See Also: numpy.NumPy Reference.imag The imaginary part of the array.flatiter instance. 3) >>> x array([[1.imag array([ 0.70710678]) >>> x.reshape(2.sqrt([1+0j. 0+1j]) >>> x. [3.sqrt([1+0j. 6]]) >>> x. 0. 5].70710678]) >>> x.. flatiter Examples >>> x = np.. . Release 1. [2.8. 4. This is a numpy.T.]) ndarray. The N-dimensional array (ndarray) 41 .dtype dtype(’float64’) ndarray. 3]. [4.flat[3] 5 1.]) 2. 0.arange(1. Python’s built-in iterator object.T array([ 1.imag. 2. 2. 4]. 0+1j]) >>> x. but is not a subclass of. Examples >>> x = np. See Also: flatten Return a copy of the array collapsed into one dimension.. >>> x. which acts similarly to.

flat) <type ’numpy.c_double)). 3.4]] = 1. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.c_longlong).ctypeslib. This ctypes array contains the strides information from the underlying array.flat[[1. Parameters None Returns c : Python object Possessing attributes data. For example: •strides_as(obj): Return the strides tuple as an array of some other c-types type. The c_intp type is defined accordingly in numpy.1 >>> type(x. The returned object has.data_as(ctypes. •shape (c_intp*self. etc. 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. calling self. The ctypes array contains the shape of the underlying array. shape. data.strides_as(ctypes.ctypeslib Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes.shape_as(ctypes. among others.c_short). The memory area may not even be writeable. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.POINTER(ctypes. 42 •shape_as(obj): Return the shape tuple as an array of some other c-types type.ndim): A ctypes array of length self. 3]]) ndarray. or c_longlong depending on the platform. c_long. strides._as_parameter_ is equivalent to self. x array([[3. 3.8. Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self. 3].c_void_p). For example: Chapter 1._array_interface_[’data’][0].ndim where the basetype is the same as for the shape attribute. 3]. Release 1.NumPy Reference. This memory area may contain data that is not aligned. [3. 3]]) >>> x.flatiter’> An assignment example: >>> x.ndim): A ctypes array of length self. [3. •data_as(obj): Return the data pointer cast to a particular c-types object. 1. User Beware! The value of this attribute is exactly the same as self.data_as(ctypes. For example.ctypes An object to simplify the interaction of the array with the ctypes module. x array([[3.ndim where the basetype is the C-integer corresponding to dtype(‘p’) on this platform.flat = 3. •strides (c_intp*self. shape. or not in correct byte-order. as well as documented private attributes): •data: A pointer to the memory area of the array as a Python integer. 1. See Also: numpy. self. self. Array objects . This base-type could be c_int.

_internal.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. 3]]) >>> x. Release 1.shape <numpy. If the ctypes module is not available._internal.8.shape_as(ctypes.POINTER(ctypes.ctypes.c_longlong)). and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.data 30439712 >>> x.1 Be careful using the ctypes attribute .c_long_Array_2 object at 0x01FCE620> >>> x.c_long_Array_2 object at 0x01FFD580> >>> x. The returned object has. __array_interface__ __array_struct__ Python-side of the array interface C-side of the array interface ctypes foreign function interface ndarray.ctypes. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. In the latter case.data_as(ctypes.especially on temporary arrays or arrays constructed on the fly.ctypes. 1]. ct will hold a reference to the array until ct is deleted or re-assigned.core. Examples >>> import ctypes >>> x array([[0. Parameters None 1. [2. In particular.c_longlong_Array_2 object at 0x01F01300> Array interface See Also: The Array Interface._internal.c_longlong) <numpy.data_as(ctypes.ctypes. You can avoid this problem using either c=a+b or ct=(a+b).c_long)) <ctypes.strides <numpy. the object will still have the as parameter attribute which will return an integer equal to the data attribute.ctypes.ctypes.c_long_Array_2 object at 0x01FCE620> >>> x.POINTER(ctypes.ctypes. For example. data.strides_as(ctypes. ndarray.contents c_longlong(4294967296L) >>> x.c_long)).core. The N-dimensional array (ndarray) 43 .data_as(ctypes. shape. calling (a+b).ctypes. but ctypes objects are not returned and errors may be raised instead.contents c_long(0) >>> x.ctypes An object to simplify the interaction of the array with the ctypes module. then the ctypes attribute of array objects still returns something useful.LP_c_long object at 0x01F01300> >>> x.c_long) <numpy. among others.1.data_as(ctypes.core.core.POINTER(ctypes.ctypes An object to simplify the interaction of the array with the ctypes module._internal.NumPy Reference.ctypes.

data_as(ctypes. Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.ctypes. then the ctypes attribute of array objects still returns something useful.especially on temporary arrays or arrays constructed on the fly.c_short). If the ctypes module is not available.contents 44 Chapter 1.data_as(ctypes.c_long)). The ctypes array contains the shape of the underlying array. This ctypes array contains the strides information from the underlying array.c_longlong).POINTER(ctypes. See Also: numpy. Release 1. Array objects .data_as(ctypes.strides_as(ctypes. The c_intp type is defined accordingly in numpy. 1].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. self.8.c_double)). This strides information is important for showing how many bytes must be jumped to get to the next element in the array. as well as documented private attributes): •data: A pointer to the memory area of the array as a Python integer._as_parameter_ is equivalent to self.ctypes.ctypes. •shape_as(obj): Return the shape tuple as an array of some other c-types type._array_interface_[’data’][0].ctypes. User Beware! The value of this attribute is exactly the same as self.ndim): A ctypes array of length self.ndim where the basetype is the same as for the shape attribute. self. or not in correct byte-order.data_as(ctypes.data_as(ctypes.POINTER(ctypes. •shape (c_intp*self. For example. but ctypes objects are not returned and errors may be raised instead. or c_longlong depending on the platform. For example: •strides_as(obj): Return the strides tuple as an array of some other c-types type. calling self. For example: Be careful using the ctypes attribute . In the latter case. ct will hold a reference to the array until ct is deleted or re-assigned. This memory area may contain data that is not aligned.c_void_p).ctypeslib Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes.LP_c_long object at 0x01F01300> >>> x.data 30439712 >>> x.ctypeslib. etc. calling (a+b).ctypes. •strides (c_intp*self.1 Returns c : Python object Possessing attributes data.c_long)) <ctypes. [2.NumPy Reference. •data_as(obj): Return the data pointer cast to a particular c-types object. shape. 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.ndim): A ctypes array of length self. Examples >>> import ctypes >>> x array([[0. In particular.POINTER(ctypes. the object will still have the as parameter attribute which will return an integer equal to the data attribute.shape_as(ctypes. For example. The memory area may not even be writeable. This base-type could be c_int. c_long.ndim where the basetype is the C-integer corresponding to dtype(‘p’) on this platform. You can avoid this problem using either c=a+b or ct=(a+b). strides. 3]]) >>> x.

8. • tuple of int_types: functions as does a single int_type argument. Parameters *args : Arguments (variable number and type) • none: in this case. ndarray.setflags([write. • int_type: this argument is interpreted as a flat index into the array. take.dumps() ndarray.byteswap(inplace) ndarray. Write array to a file as text or binary (default). which element is copied into a standard Python scalar object and returned.core.dump(file) ndarray. sep. offset]) ndarray. sum.) For the following methods there are also corresponding functions in numpy: all. except that the argument is 1. mean.ctypes. Dump a pickle of the array to the specified file. cast to a specified type.tostring([order]) ndarray. Set array flags WRITEABLE.5 Array methods An ndarray object has many methods which operate on or with the array in some fashion.fill(value) Copy an element of an array to a standard Python scalar and return it. squeeze. ptp. partition. order._internal. if possible) Construct a Python string containing the raw data bytes in the array. compress. trace.view([dtype.tolist() ndarray. . repeat.item(*args) Copy an element of an array to a standard Python scalar and return it. put.]) ndarray.c_longlong)).c_long_Array_2 object at 0x01FCE620> >>> x. the method only works for arrays with one element (a.shape_as(ctypes.ctypes. type]) ndarray..itemset(*args) ndarray. specifying which element to copy and return.contents c_longlong(4294967296L) >>> x. argpartition._internal. imag.. typically returning an array result. The N-dimensional array (ndarray) 45 . sort.c_longlong_Array_2 object at 0x01F01300> 1. transpose.tofile(fid[. reshape. swapaxes. Insert scalar into an array (scalar is cast to array’s dtype.shape <numpy. Copy of the array.1. ravel.NumPy Reference.setasflat ndarray.ctypes.c_long_Array_2 object at 0x01FCE620> >>> x.copy([order]) ndarray. cumprod. nonzero.c_long) <numpy._internal. These methods are briefly explained below. format]) ndarray.core.1. uic]) ndarray. std.core. casting.c_long_Array_2 object at 0x01FFD580> >>> x. respectively. Release 1. (Each method’s docstring has a more complete description. prod. real. searchsorted.data_as(ctypes. round. Swap the bytes of the array elements Return a copy of the array. choose. copy. ALIGNED. min. Fill the array with a scalar value. align. Returns a field of the given array as a certain type.c_longlong) <numpy.astype(dtype[. cumsum.size == 1). diagonal. Return the array as a (possibly nested) list. and UPDATEIFCOPY. clip. any. argmin. argsort.strides_as(ctypes.POINTER(ctypes. argmax. Array conversion ndarray. var. Returns the pickle of the array as a string.strides <numpy.1 c_long(0) >>> x.getfield(dtype[. New view of array with the same data. max.core.item(*args) ndarray.ctypes.ctypes._internal.

Void arrays return a buffer object for item(). 2)) 3 ndarray. 3]]) >>> x. [8.8. Return a copy of the array data as a (nested) Python list. Examples >>> x = np. 5. 3]. [3. a standard Python scalar is returned.tolist() [1. item is very similar to a[args]. 4]] 46 Chapter 1.item((2.tolist() Return the array as a (possibly nested) list.tolist() [[1.array(a. 2]. [3. except. Data items are converted to the nearest compatible Python type.tolist()). 2]).NumPy Reference. array([3. size=(3. Examples >>> a = np. 3)) >>> x array([[3. 7].array([[1. 1)) 1 >>> x.random. 2] >>> a = np. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.1 interpreted as an nd-index into the array. Release 1.array([1. 2]. Array objects .item(7) 5 >>> x. a = np. instead of an array scalar.item((0.randint(9. 2]) >>> a. Notes The array may be recreated. unless fields are defined. in which case a tuple is returned. 1. Parameters none Returns y : list The possibly nested list of array elements. 4]]) >>> list(a) [array([1. 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. 4])] >>> a. 8.item(3) 2 >>> x. [2.

itemset(*args) is equivalent to but faster than a[args] = item. in which case it means ‘Fortran’ order. Examples >>> x = np. 7]. However. or ‘Any’ order (the default is ‘C’-order). ‘Any’ order means C-order unless the F_CONTIGUOUS flag in the array is set. generally this is discouraged: among other problems.array([[0. The item should be a scalar value and args must select a single item in the array a. 3)) >>> x array([[3. 0) >>> x. 3]. [2. Release 1. 3]]) >>> x. Returns s : str A Python string exhibiting a copy of a‘s raw data. Notes Compared to indexing syntax.1.random. or the same as for the original array. 5.itemset(4. itemset provides some speed increase for placing a scalar into a particular location in an ndarray. 9]]) ndarray.randint(9. only used in case a is of size 1. Then. 1. 0. It is either an int or a tuple. 3]. a. ‘F’. the first argument specifies a single array element location.itemset((2. [2.tostring(order=’C’) Construct a Python string containing the raw data bytes in the array.NumPy Reference. [8. If two arguments: the last argument is the value to be set and must be a scalar.tostring() ’\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00’ >>> x. 9) >>> x array([[3.itemset(*args) Insert scalar into an array (scalar is cast to array’s dtype. 5.tostring(’C’) == x. The string can be produced in either ‘C’ or ‘Fortran’. 7]. and define the last argument as item. Examples >>> x = np.tostring() True 1. Fortran. Constructs a Python string showing a copy of the raw contents of data memory. optional Order of the data for multidimensional arrays: C. 3]]) >>> x. [8. it complicates the appearance of the code. The N-dimensional array (ndarray) 47 . 8. if you must do this. Parameters *args : Arguments If one argument: a scalar. when using itemset (and item) inside a loop. if possible) There must be at least 1 argument.1 ndarray.8. 1]. Also. [2. size=(3. None}. 2). 1. be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration. Parameters order : {‘C’.

Release 1. subok=True. Defaults to ‘unsafe’ for backwards compatibility. ‘safe’. and ‘K’ means as close to the order the array elements appear in memory as possible. ndarray. Data is always written in ‘C’ order. Array objects .tofile(fid. The array can be read back with pickle. Parameters None ndarray.load. cast to a specified type. optional Controls what kind of data casting may occur. ‘same_kind’. and then using “format” % item. independent of the order of a. or a string containing a filename. optional Controls the memory layout order of the result. order : {‘C’. casting=’unsafe’.8. copy=True) Copy of the array. ‘C’ means C order. ‘unsafe’}. ‘A’ means ‘F’ order if all the arrays are Fortran contiguous. sep : str Separator between array items for text output.tostring()). ‘A’. Each entry in the array is formatted to text by first converting it to the closest Python type.1 >>> x. Some of these problems can be overcome by outputting the data as text files. Default is ‘K’. ndarray.astype(dtype. The data produced by this method can be recovered using the function fromfile(). pickle. Notes This is a convenience function for quick storage of array data.write(a. ‘K’}. Information on endianness and precision is lost. Parameters dtype : str or dtype Typecode or data-type to which the array is cast. order=’K’. Parameters file : str A string naming the dump file. Parameters fid : file or str An open file object.load or numpy. format=”%s”) Write array to a file as text or binary (default).dump(file) Dump a pickle of the array to the specified file. 48 Chapter 1. ‘F’. a binary file is written. ‘C’ order otherwise. at the expense of speed and file size. equivalent to file.NumPy Reference.loads or numpy. ‘equiv’. format : str Format string for text file output. casting : {‘no’. If “” (empty). ‘F’ means Fortran order.loads will convert the string back to an array.tostring(’F’) ’\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00’ ndarray.dumps() Returns the pickle of the array as a string. so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. sep=”“.

optional If True. then sub-classes will be passed-through (default). • ‘unsafe’ means any data conversions may be done. 2. • ‘safe’ means only casts which can preserve values are allowed. and the dtype. Examples 1.5]) >>> x array([ 1. subok : bool. one should use Examples >>> x = np. the input array is returned instead of a copy. • ‘equiv’ means only byte-order changes are allowed. 2.array([1. Returns arr_t : ndarray Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input paramter). 2. 2]) ndarray.5]) >>> x. default is False. Raises ComplexWarning When casting from complex to float or int. optional By default. order. Release 1. .1 • ‘no’ means the data types should not be cast at all. a. this is a view to self. and subok requirements are satisfied.NumPy Reference. are allowed. order given by dtype. • ‘same_kind’ means only safe casts or casts within a kind. otherwise the returned array will be forced to be a base-class array. copy : bool.real.1. Parameters inplace : bool. arr_t is a new array of the same shape as the input array. like float64 to float32. If this is set to false.byteswap(inplace) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array. 2. To avoid this. optionally swapped in-place. astype always returns a newly allocated array.astype(t). 2. If inplace is True. optional If True. Returns out : ndarray The byteswapped array. order.astype(int) array([1. . swap bytes in-place. The N-dimensional array (ndarray) 49 .8. with dtype.

optional 50 Chapter 1. type=None) New view of array with the same data. 0. ‘F’ means F-order.1 >>> A = np.NumPy Reference. 256. 13090]. 3]. but have different default values for their order= arguments. numpy.copy() >>> x.flags[’C_CONTIGUOUS’] True ndarray. type : Python type. Parameters dtype : data-type or ndarray sub-class. ’fac’]) >>> A. ’fac’].) See Also: numpy.byteswap() array([’ceg’. ‘K’}. [0.copy. ’0x1’. 0]]) >>> y array([[1.copy(order=’C’) Return a copy of the array. ’0x3322’] Arrays of strings are not swapped >>> A = np.g.fill(0) >>> x array([[0. 6]]) >>> y.[4.6]]. ‘K’ means match the layout of a as closely as possible.5.array([[1. 8755]..array([1. which then specifies the type of the returned object (this is equivalent to setting the type parameter).byteswap(True) array([ 256. Parameters order : {‘C’. float32 or int16.int16) >>> map(hex. order=’F’) >>> y = x. ’0x100’. ’0x2233’] >>> A. dtype=np.8.copyto Examples >>> x = np.2. results in the view having the same data-type as a. A) [’0x1’. optional Controls the memory layout of the copy. ‘A’. A) [’0x100’. ‘C’ otherwise.array([’ceg’. ‘A’ means ‘F’ if a is Fortran contiguous. ‘C’ means C-order. The default. dtype=int16) >>> map(hex. e. dtype=’|S3’) ndarray. This argument can also be specified as an ndarray sub-class. None. 0. [4. Release 1.copy are very similar. 1. optional Data-type descriptor of the returned view. 2.3]. 0]. 5. (Note that this function and :func:numpy. Array objects .view(dtype=None. ‘F’.

array([(1. the default None results in type preservation.a array([1]. dtype=[(’a’. (’b’. The N-dimensional array (ndarray) 51 . 3. the view may give different results. type=np.defmatrix. dtype.view(dtype=np.view(np. 10) 1.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape. dtype=int8) >>> xv. For a. 2).NumPy Reference.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type.int8). Notes a.int8). np. Again. etc.view(dtype=np. e.4)].) This does not cause a reinterpretation of the memory.1. etc. np. This can cause a reinterpretation of the bytes of memory.8.reshape(-1.view(some_dtype) or a.1 Type of the returned view.view(ndarray_subclass) or a.view() is used two different ways: a.. a.g.2) >>> xv array([[1. 4]].view(some_dtype).int16.int8)]) >>> xv = x.matrixlib. 2]. 10) >>> z[0] (9. Release 1. 4)] Using a view to convert an array to a record array: >>> z = x. then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)).int8). Therefore if a is C-ordered versus fortran-ordered. converting a regular array to a structured array). 2)].array([(1. np. It also depends on exactly how a is stored in memory.. 20) (3. (’b’.recarray) >>> z.1] = 20 >>> print x [(1.matrix) >>> y matrix([[513]].matrix’> Creating a view on a structured array so it can be used in calculations >>> x = np.(3. dtype=int16) >>> print type(y) <class ’numpy. if some_dtype has a different number of bytes per entry than the previous dtype (for example. [3..int8)]) Viewing array data using a different type and dtype: >>> y = x. versus defined as a slice or transpose. ndarray or matrix. Examples >>> x = np.mean(0) array([ 2. np. dtype=[(’a’. dtype=int8) Views share data: >>> x[0] = (9.]) Making changes to the view changes the underlying array >>> xv[0.

float64. ALIGNED. 0. 0. dtype=np.getfield(np. (’length’. The ALIGNED flag can only be set to True if the data is actually aligned according to the type.. [(4.+4. [ 0.getfield(np. uic=None) Set array flags WRITEABLE. 2].int16).]]) ndarray..8. If taking a view with a 32-bit integer (4 bytes). dtype=int16) >>> y.view(dtype=[(’width’.int16)]) Traceback (most recent call last): File "<stdin>". or is a string. np. Release 1.j. align=None. ’<i2’)]) ndarray.j >>> x array([[ 1. np. 2. the offset needs to be between 0 and 12 bytes. np. 0. 5]]. The values in the view are determined by the given type and the offset into the current array in bytes.: >>> x = np.j]*2) >>> x[1.j]]) >>> x.6]]. np. Examples >>> x = np.5. ’<i2’). A field is a view of the array data with a given data-type..j].getfield(dtype.+0.[4.view(dtype=[(’width’.copy() >>> z. or the ultimate owner of the memory exposes a writeable buffer interface. >>> z = y. 1] = 2 + 4.int16) >>> y = x[:. offset : int Number of bytes to skip before beginning the element view.+0. (’length’. 0:2] >>> y array([[1..].array([[1. in <module> ValueError: new type not compatible with array. offset=0) Returns a field of the given array as a certain type. transposes. dtype=[(’width’. 5)]].]. The dtype size of the view can not be larger than that of the array itself.1 Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices.+1. offset=8) array([[ 1. The flag WRITEABLE can only be set to True if the array owns its own memory. [4.int16)]) array([[(1. fortran-ordering.float64) array([[ 1. The UPDATEIFCOPY flag can never be set to True. for example an array of dtype complex128 has 16-byte elements. etc. 2. line 1. and UPDATEIFCOPY. The offset needs to be such that the view dtype fits in the array dtype. These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below).diag([1. 4. respectively.]]) By choosing an offset of 8 bytes we can select the complex part of the array for our view: >>> x.int16).NumPy Reference. (The exception for string is made so that unpickling can be done without copying memory. 2)]. (’length’.3].+1.j. Array objects .) 52 Chapter 1. Parameters dtype : str or dtype The data type of the view. [ 0. [ 0.2.setflags(write=None.

7].1. [8. uic : bool. Release 1. 0.8.base). align : bool. All flags can be accessed using their first (upper case) letter as well as the full name. the base array will be updated with the contents of this array.fill(value) Fill the array with a scalar value. only three of which can be changed by the user: UPDATEIFCOPY.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y. 0]. 1. 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.setflags(write=0.1 Parameters write : bool. [2. WRITEABLE. UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .NumPy Reference. optional Describes whether or not a can be written to. align=0) >>> y. There are 6 Boolean flags in use.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>". optional Describes whether or not a is aligned properly for its type. and ALIGNED. WRITEABLE (W) the data area can be written to. Examples >>> y array([[3. line 1. in <module> ValueError: cannot set UPDATEIFCOPY flag to True ndarray. Parameters value : scalar All elements of a will be assigned this value. 1. 9]]) >>> y. The N-dimensional array (ndarray) 53 . ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler). When this array is deallocated. 5.

axis2) ndarray. Returns a view of the array with axes transposed.NumPy Reference.resize(new_shape[.reshape(shape[.. and transpose.1 Examples >>> a = np. Return a copy of the array collapsed into one dimension. and the data memory must be changed.ravel([order]) ndarray.flatten([order]) ndarray. Returns None Raises ValueError If a does not own its own data or references or views to it exist. Array objects .squeeze([axis]) Returns an array containing the same data with a new shape.fill(0) >>> a array([0.swapaxes(axis1.fill(1) >>> a array([ 1. Release 1. 54 Chapter 1.empty(2) >>> a. Return a flattened array. refcheck]) ndarray.resize(new_shape.reshape equivalent function ndarray.transpose(*axes) ndarray.8. reference count will not be checked.reshape for full documentation. See Also: numpy. Default is True. or n ints Shape of resized array. Parameters new_shape : tuple of ints. the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple. ndarray. This behaviour is a bug in NumPy. resize. 0]) >>> a = np. 2]) >>> a. Return a view of the array with axis1 and axis2 interchanged. order=’C’) Returns an array containing the same data with a new shape. Refer to numpy. optional If False. order]) ndarray. 1. Remove single-dimensional entries from the shape of a.]) Shape manipulation For reshape. ndarray.array([1. Change shape and size of array in-place. SystemError If the order keyword argument is specified. refcheck=True) Change shape and size of array in-place.reshape(shape. refcheck : bool.

transpose(*axes) Returns a view of the array with axes transposed. 0]]) Referencing an array prevents resizing. this is the usual matrix transpose. 1]..resize((2. >>> c = a >>> a.1 See Also: resize Return a new array with the specified shape. Only contiguous arrays (data elements consecutive in memory) can be resized.array([[0.resize((2. and reshaped: >>> a = np. For a 1-D array. 1).resize((1. 0.array([[0.NumPy Reference. Examples Shrinking an array: array is flattened (in the order that the data are stored in memory). 1]. 3) # new_shape parameter doesn’t have to be a tuple >>> b array([[0. Unless refcheck is False: >>> a. order=’F’) >>> a. first cast the 1-D array into a matrix object.. 1]. [2.. this has no effect. 1. 3]]) >>> b.. their order in1. ValueError: cannot resize an array that has been referenced .1. 1)) Traceback (most recent call last): .. [2]]) Enlarging an array: as above.. if axes are given.resize((1. [1]]) >>> a = np. (To change between column and row vectors. order=’C’) >>> a. then you may safely set refcheck to False. However. 1)) >>> a array([[0]. [2.) For a 2-D array. 1)) >>> a array([[0]. refcheck=False) >>> a array([[0]]) >>> c array([[0]]) ndarray. The N-dimensional array (ndarray) 55 .array([[0. [2.8. Notes This reallocates space for the data area if necessary. For an n-D array. 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. 3]]. Release 1. [3. 2]. resized.resize(2. 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. but missing entries are filled with zeros: >>> b = np. 3]].

Parameters axes : None.swapaxes for full documentation. ‘F’. [3. i[n-1]). The default is ‘C’.shape = (i[n-1]. . i[0]).8. ‘A’}. 4]]) >>> a. [3. i[1]. Refer to numpy.. i[1]. tuple of ints.swapaxes(axis1. 4]]) >>> a array([[1. or preserve the C/Fortran ordering from a. then a.. axis2) Return a view of the array with axis1 and axis2 interchanged. [2. optional Whether to flatten in C (row-major). 2].. See Also: numpy. 3]. 2]. If axes are not provided and a. See Also: ndarray.swapaxes equivalent function ndarray.array([[1.transpose(1. 4]]) >>> a. 3]. 0) array([[1.transpose((1. [2. or n ints • None or no argument: reverses the order of the axes. . with axes suitably permuted. 3].T Array property returning the array transposed.1 dicates how the axes are permuted (see Examples). [2. Array objects . Returns y : ndarray 56 Chapter 1.flatten(order=’C’) Return a copy of the array collapsed into one dimension. i[n-2].shape = (i[0]. 4]]) ndarray.transpose() array([[1.. 0)) array([[1. Release 1.transpose(). • 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. i[n-2]. Parameters order : {‘C’. Fortran (column-major) order.transpose()‘s j-th axis.NumPy Reference. • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a. Examples >>> a = np. 4]]) >>> a.

3. axis. mode]) ndarray. [3. Returns the indices that would sort this array.2]. mode]) ndarray.flatten() array([1. Set a. Release 1. 3.ravel for full documentation. order]) ndarray. out. Examples >>> a = np. If axis is None. then the array is treated as a 1-D array. See Also: numpy.flat a flat iterator on the array. order]) ndarray.8. in-place. Rearranges the elements in the array in such a way that value of the element i Returns the indices that would partition this array.array([[1.take(indices[.1.choose(choices[. flat A 1-D flat iterator over the array. order]) ndarray. 57 .argpartition(kth[. axis]) ndarray.searchsorted(v[.ravel equivalent function ndarray.NumPy Reference.4]]) >>> a. side. sorter]) ndarray. 2. values[. Repeat elements of an array. See Also: ravel Return a flattened array. 2. Refer to numpy. See Also: numpy. 4]) ndarray. kind. flattened to one dimension. Sort an array. Use an index array to construct a new array from a set of choices. kind. Find indices where elements of v should be inserted in a to maintain order. kind.repeat(repeats[.1 A copy of the input array.ravel([order ]) Return a flattened array.squeeze for full documentation. out.flatten(’F’) array([1. Any other value for axis represents the dimension along which the operation should proceed. Refer to numpy.partition(kth[. axis.put(indices. ndarray.sort([axis. mode]) ndarray. The N-dimensional array (ndarray) Return an array formed from the elements of a at the given indices. kind.argsort([axis.squeeze(axis=None) Remove single-dimensional entries from the shape of a.nonzero() 1. order]) ndarray. Return the indices of the elements that are non-zero. it defaults to None.squeeze equivalent function Item selection and manipulation For array methods that take an axis keyword.flat[n] = values[n] for all n in indices. ndarray. 4]) >>> a. axis.

ndarray. this argument specifies which fields to compare first.choose for full documentation.repeat(repeats. second. order : list. mode=’raise’) Return an array formed from the elements of a at the given indices. Refer to numpy. optional When a is an array with fields defined. out=None. ‘mergesort’. in-place.8.put(indices. Refer to numpy. Array objects .sort(axis=-1.take for full documentation. Parameters axis : int. See Also: numpy. Refer to numpy. optional Axis along which to sort.choose equivalent function ndarray. axis.1 ndarray. Default is ‘quicksort’.flat[n] = values[n] for all n in indices. out=None.diagonal([offset.put for full documentation. 58 Chapter 1.10 – continued from previous page Return selected slices of this array along given axis. which means sort along the last axis. optional Sorting algorithm.choose(choices.compress(condition[. etc. values. kind=’quicksort’.put equivalent function ndarray. mode=’raise’) Set a. axis=None. Default is -1. axis=None) Repeat elements of an array.NumPy Reference. See Also: numpy. kind : {‘quicksort’. See Also: numpy. Not all fields need be specified.take(indices.repeat for full documentation. Refer to numpy. Release 1. order=None) Sort an array. mode=’raise’) Use an index array to construct a new array from a set of choices. Return specified diagonals. See Also: numpy.take equivalent function ndarray. ‘heapsort’}.repeat equivalent function ndarray. axis2]) Table 1. out]) ndarray. axis1.

1 See Also: numpy.4].argsort equivalent function ndarray. int)]) >>> a. lexsort Indirect stable sort on multiple keys. 2). Parameters kth : int or sequence of ints 1.argsort for full documentation. 3]]) >>> a.8. argsort Indirect sort.0. See Also: numpy. kind=’quicksort’.8. partition Partial sort. Refer to numpy.array([(’a’.partition(kth. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it.sort(axis=1) >>> a array([[1. Release 1. 2)]. ’<i4’)]) ndarray. The N-dimensional array (ndarray) 59 . order=None) Returns the indices that would sort this array. The ordering of the elements in the two partitions is undefined. dtype=[(’x’. dtype=[(’x’. order=None) Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array. [3.sort Return a sorted copy of an array. [1. ’|S1’). Notes See sort for notes on the different sorting algorithms.1.argsort(axis=-1. kind=’introselect’.1]]) >>> a. 1)]. ’S1’). (’c’. (’a’.sort(axis=0) >>> a array([[1. [1. 1). axis=-1. (’y’. 3].NumPy Reference. searchsorted Find elements in sorted array. 4].array([[1. New in version 1.sort(order=’y’) >>> a array([(’c’. Examples >>> a = np. 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> a = np. (’y’.

sorter=None) Find indices where elements of v should be inserted in a to maintain order. See Also: numpy. optional Selection algorithm. argpartition Indirect partition.1 Element index to partition by. see numpy. side=’left’. axis=-1. 1]) >>> a. See Also: numpy.argpartition equivalent function ndarray. Release 1.8. 3. 2. Examples >>> a = np.8.NumPy Reference. axis : int.argpartition(kth. sort Full sort. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.searchsorted See Also: numpy. 4]) ndarray.partition Return a parititioned copy of an array. Array objects .partition for notes on the different algorithms. optional Axis along which to sort. 3. etc. kind=’introselect’. The order all elements in the partitions is undefined. which means sort along the last axis. Default is -1. 3) >>> a array([2. Default is ‘introselect’.searchsorted equivalent function 60 Chapter 1. 4.array([3. 2. 3)) array([1.searchsorted(v. Notes See np. optional When a is an array with fields defined. New in version 1. Refer to numpy. this argument specifies which fields to compare first.partition((1. For full documentation. order : list. Not all fields need be specified.partition(a. 4]) >>> a. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. 1. kind : {‘introselect’}.0. second.argpartition for full documentation. order=None) Returns the indices that would partition this array.

22.1.1 ndarray. 20]. out=None) Return selected slices of this array along given axis. [21. 23]. 16. 30. [24.8. See Also: numpy. In such cases.) • If axis is an integer. 11]. Refer to numpy. 33]. • If axis is None (the default). 2]. the array is treated as a 1-D array and the operation is performed over the entire array. [12. Refer to numpy. Refer to numpy. 26]]]) >>> x. [[ 9. The N-dimensional array (ndarray) 61 .diagonal(offset=0. 10. float64.nonzero for full documentation.. [36. 8]].diagonal equivalent function Calculation Many of these methods take an argument named axis. 19. 25. See Also: numpy. 39.diagonal for full documentation. [15. 1. 17]]. then the operation is done over the given axis (for each 1-D subarray that can be created along the given axis). [ 3. This behavior is also the default if self is a 0-dimensional array or array scalar. whereas a 0-dimensional array is an ndarray instance containing precisely one array scalar.compress for full documentation.sum(axis=0) array([[27. 14]. 1. [ 6.NumPy Reference.compress(condition. 13. 4. axis2=1) Return specified diagonals. etc.compress equivalent function ndarray. axis=None. Release 1. 42]. See Also: numpy. axis1=0. summed over each of its three axes >>> x array([[[ 0. [[18. 7.nonzero() Return the indices of the elements that are non-zero. Example of the axis argument A 3-dimensional array of size 3 x 3 x 3. (An array scalar is an instance of the types/classes float32. 5].nonzero equivalent function ndarray.

any([axis. [57. array([[ 3.amin for full documentation. Return an array whose values are limited to [a_min. dtype. dtype. ddof]) ndarray. [36. out]) ndarray. 66. 39.cumsum([axis. 42]. See Also: numpy. 42]. out]) Return indices of the maximum values along the given axis. out]) ndarray. Return the cumulative sum of the elements along the given axis. axis2.prod([axis. axis is the first keyword. dtype.argmax(axis=None.1 [45. 12. out]) ndarray. 39. out]) ndarray. out]) ndarray. x. out]) ndarray. out]) ndarray. array([[ 9. [30. 51]]) >>> # for sum. 48. out]) ndarray. [45.cumprod([axis. out=None) Return the minimum along a given axis. 62 Chapter 1. [63. Returns the standard deviation of the array elements along given axis. 30. Refer to numpy.std([axis. Return the sum of the array elements over the given axis. Returns True if any of the elements of a evaluate to True. out]) ndarray.clip(a_min. 51]]). Return the sum along diagonals of the array. it can be useful to perform the reduction using a larger data type. out]) ndarray.ptp([axis.argmax for full documentation. axis1. a_max[.minimum) value along a given axis. Return the product of the array elements over the given axis Return the cumulative product of the elements along the given axis. 48. [36. dtype. dtype. dtype.mean([axis. an optional out argument can also be provided and the result will be placed into the output array given. Return the minimum along a given axis. 48]. Returns True if all elements evaluate to True. a_max]. Return indices of the minimum values along the given axis of a. >>> # specifying only its value >>> x. ddof]) ndarray. along given axis. To avoid overflow.NumPy Reference. out]) ndarray. out=None) Return indices of the maximum values along the given axis. 21]. Refer to numpy. 66.8. Returns the average of the array elements along given axis.min(axis=None. Array objects . Release 1. out]) ndarray. Complex-conjugate all elements. 33]. out]) ndarray.sum(0). The default reduce data type is the same as the data type of self. Return a with each element rounded to the given number of decimals. dtype. ndarray.round([decimals.sum(2) (array([[27. ndarray. out. 39. so we may omit it. 69]]). Peak to peak (maximum .var([axis.sum([axis.argmin([axis.min([axis.argmax equivalent function ndarray. out.argmax([axis.all([axis. For several methods.conj() ndarray. 15]. dtype. The out argument must be an ndarray and have the same number of elements.sum(1). 75]])) The parameter dtype specifies the data type over which a reduction operation (like summing) should take place. It can have a different data type in which case casting will be performed. 12.trace([offset. Returns the variance of the array elements. x.

minimum) value along a given axis.ptp(axis=None.around equivalent function ndarray. Refer to numpy.conjugate equivalent function ndarray.trace(offset=0.NumPy Reference.conj() Complex-conjugate all elements. out=None) Return an array whose values are limited to [a_min. axis2=1. Release 1. a_max.clip for full documentation. axis1=0. See Also: numpy.clip(a_min. out=None) Return indices of the minimum values along the given axis of a. Refer to numpy.ptp equivalent function ndarray. out=None) Peak to peak (maximum . Refer to numpy.1 See Also: numpy. 1. Refer to numpy. out=None) Return the sum along diagonals of the array. The N-dimensional array (ndarray) 63 .trace for full documentation. Refer to numpy.argmin for detailed documentation.8.amin equivalent function ndarray. See Also: numpy. a_max].clip equivalent function ndarray. dtype=None.argmin equivalent function ndarray. Refer to numpy.ptp for full documentation.1. See Also: numpy. See Also: numpy. out=None) Return a with each element rounded to the given number of decimals. See Also: numpy.around for full documentation.conjugate for full documentation.round(decimals=0.argmin(axis=None.

dtype=None.cumsum equivalent function ndarray.std for full documentation.cumsum(axis=None.sum equivalent function ndarray. out=None) Return the product of the array elements over the given axis Refer to numpy. dtype=None. Refer to numpy. dtype=None. ddof=0) Returns the variance of the array elements.sum(axis=None.sum for full documentation. Array objects . dtype=None. dtype=None.prod(axis=None.1 See Also: numpy. out=None) Returns the average of the array elements along given axis. See Also: numpy. Refer to numpy. 64 Chapter 1. out=None. ddof=0) Returns the standard deviation of the array elements along given axis. Refer to numpy.std(axis=None.var(axis=None. See Also: numpy. See Also: numpy.mean equivalent function ndarray.NumPy Reference. out=None) Return the cumulative sum of the elements along the given axis.std equivalent function ndarray.cumsum for full documentation.prod for full documentation. along given axis. out=None) Return the sum of the array elements over the given axis.var equivalent function ndarray.mean for full documentation. Refer to numpy. See Also: numpy.8.mean(axis=None.var for full documentation. out=None. See Also: numpy. dtype=None.trace equivalent function ndarray. Refer to numpy. Release 1.

all equivalent function ndarray. out=None) Returns True if all elements evaluate to True.__le__ ndarray. See Also: numpy.all for full documentation.__ne__ x.__gt__ ndarray. See Also: numpy.__ne__(y) <==> x!=y ndarray.__eq__ ndarray. -. ^. <=.__lt__ ndarray.1. Refer to numpy.__lt__(y) <==> x<y ndarray.__lt__(y) <==> x<y x. >>. %.cumprod equivalent function ndarray. /.__ge__ ndarray. divmod().any equivalent function 1.1.8.__le__ 1. dtype=None.__ge__(y) <==> x>=y x.__lt__ x.NumPy Reference. !=) is equivalent to the corresponding universal function (or ufunc for short) in Numpy. Comparison operators: ndarray. *. <<. Release 1. //. ~) and the comparisons (==.cumprod(axis=None. ** or pow().1 See Also: numpy. &.__gt__(y) <==> x>y x. Refer to numpy.prod equivalent function ndarray. and generally yield ndarray objects as results. see the section on Universal Functions.any for full documentation. out=None) Returns True if any of the elements of a evaluate to True. >=. See Also: numpy.all(axis=None. Each of the arithmetic operations (+. |. Refer to numpy. >.__le__(y) <==> x<=y x. <. The N-dimensional array (ndarray) 65 .any(axis=None. For more information.__eq__(y) <==> x==y x.cumprod for full documentation.6 Arithmetic and comparison operations Arithmetic and comparison operations on ndarrays are defined as element-wise operations. out=None) Return the cumulative product of the elements along the given axis.

__add__(y) <==> x+y x.__invert__ x.__sub__(y) <==> x-y x.__eq__ x.__abs__() <==> abs(x) ndarray.__eq__(y) <==> x==y ndarray.__nonzero__() <==> x != 0 Note: Truth-value testing of an array invokes ndarray.__truediv__(y) <==> x/y x.__divmod__(y) <==> divmod(x.__truediv__ ndarray.__mul__(y) <==> x*y x.__abs__() <==> abs(x) ndarray. the array evaluates to False. Array objects .__floordiv__ ndarray.__neg__ x.any() and . (If the number of elements is 0.__floordiv__(y) <==> x//y x.__add__ ndarray.__neg__ ndarray.__invert__() <==> ~x ndarray.1 x.__gt__(y) <==> x>y ndarray.__mul__ ndarray.__mod__(y) <==> x%y Continued on next page 66 Chapter 1.__pos__ ndarray.__nonzero__.__nonzero__ x. because the truth value of such arrays is ambiguous.8.__le__(y) <==> x<=y ndarray. y) x.__mod__ ndarray.__nonzero__() <==> x != 0 ndarray.all() instead to be clear about what is meant in such cases.__pos__() <==> +x x.__sub__ ndarray.__ge__ x.__nonzero__ x.__invert__ x.__div__(y) <==> x/y x. Use . which raises an error if the number of elements in the the array is larger than 1.__ne__(y) <==> x!=y Truth value of an array (bool): ndarray.) Unary operations: ndarray.__pos__ x.__pos__() <==> +x ndarray.__ge__(y) <==> x>=y ndarray. Release 1.NumPy Reference.__neg__() <==> -x ndarray.__neg__() <==> -x x.__invert__() <==> ~x Arithmetic: ndarray.__gt__ x.__div__ ndarray.__ne__ x.

__xor__ x.__sub__ x.__sub__(y) <==> x-y ndarray.__truediv__ x.__xor__ x.__pow__(y[.__mul__ x. the __r{op}__ special methods are not directly defined. y[.NumPy Reference. The N-dimensional array (ndarray) 67 .__truediv__(y) <==> x/y ndarray. • Because ndarray is a built-in type (written in C).__add__(y) <==> x+y ndarray. z]) <==> pow(x. div is active by default. Release 1.__mul__(y) <==> x*y ndarray.1. as the underlying ufunc takes only two arguments.__floordiv__ x.__mod__ x.__pow__(y[. z]) <==> pow(x.__div__ x.__rshift__(y) <==> x>>y ndarray.__xor__(y) <==> x^y Note: • Any third argument to pow is silently ignored.__or__(y) <==> x|y ndarray.__or__ x.__rshift__ x. y[. 1.__lshift__(y) <==> x<<y ndarray.__divmod__(y) <==> divmod(x.__lshift__ x. y) ndarray.__and__(y) <==> x&y ndarray.__div__(y) <==> x/y ndarray.__and__ x.__or__ x.__lshift__ x. z]) ndarray.__lshift__(y) <==> x<<y ndarray.15 – continued from previous page ndarray.__and__ x.__rshift__(y) <==> x>>y ndarray.__mod__(y) <==> x%y ndarray.8.__and__(y) <==> x&y ndarray. • The functions called to implement many arithmetic special methods for arrays can be modified using set_numeric_ops.__or__(y) <==> x|y ndarray. z]) ndarray.__rshift__ x. truediv is active when __future__ division is in effect.1 Table 1.__floordiv__(y) <==> x//y ndarray.__add__ x.__xor__(y) <==> x^y ndarray. • The three division operators are all defined.

__iadd__(y) <==> x+=y ndarray.__imul__(y) <==> x*=y ndarray.__ixor__ x.__ilshift__ x. Release 1.__ilshift__(y) <==> x<<=y ndarray.__iand__(y) <==> x&=y x.1 Arithmetic.__irshift__ x.__ixor__(y) <==> x^=y ndarray.__ifloordiv__ x.__isub__ x.__ipow__ ndarray.__ior__ ndarray.__iadd__(y) <==> x+=y x.__ifloordiv__(y) <==> x//y x.__idiv__ ndarray.__ifloordiv__ ndarray.__ior__(y) <==> x|=y x.__isub__ ndarray.__irshift__(y) <==> x>>=y x.__imul__ ndarray.__ixor__ x.__ior__ x.__idiv__(y) <==> x/=y x.__imod__(y) <==> x%=y x.8.__ifloordiv__(y) <==> x//y ndarray.__ilshift__ ndarray.__iadd__ ndarray.__ilshift__(y) <==> x<<=y x.__iand__ ndarray.__isub__(y) <==> x-=y x.__imod__ ndarray.__irshift__(y) <==> x>>=y ndarray.__imod__(y) <==> x%=y ndarray. in-place: ndarray.__itruediv__(y) <==> x/y ndarray.__itruediv__ ndarray.__idiv__ x.__iand__ x.NumPy Reference.__imul__(y) <==> x*=y x.__idiv__(y) <==> x/=y ndarray.__ior__(y) <==> x|=y ndarray.__itruediv__ x.__ipow__(y) <==> x**=y x.__ipow__(y) <==> x**=y ndarray.__itruediv__(y) <==> x/y x.__isub__(y) <==> x-=y ndarray.__iand__(y) <==> x&=y ndarray.__ipow__ x.__ixor__(y) <==> x^=y 68 Chapter 1.__irshift__ ndarray.__imul__ x.__iadd__ x.__imod__ x. Array objects .

If order is ‘Any’ (None) then the result has fortran order only if the array already is in fortran order. If omitted defaults to 0. a subtype of T 1.1 Warning: In place operations will perform the calculation using the precision decided by the data type of the two operands.__array__(.__reduce__() ndarray. whereas a = a + 3j re-binds the name a to the result. suppose a = ones((3.__copy__([order]) ndarray. For example.. A {op}= B can be different than A = A {op} B.deepcopy is called on an array. Parameters order : {‘C’. 1. Used if copy.__new__((S. shape.) ndarray. If order is ‘Fortran’ (True) then the result has fortran order.. Therefore.. ndarray. shape.__deepcopy__() → Deep copy of array.__array_wrap__(.__reduce__() For pickling. dtype.__new__(S. Used if copy. The N-dimensional array (ndarray) 69 ...) ndarray. Then.__setstate__(version.NumPy Reference. .__setstate__(version. Release 1.. optional If order is ‘C’ (False) then the result is contiguous (default).8. ndarray. rawdata) For unpickling. but will silently downcast the result (if necessary) so it can fit back into the array. .deepcopy is called on an array.__copy__([order ]) Return a copy of the array.1. shape : tuple dtype : data-type isFortran : bool rawdata : string or list a binary string with the data (or a list if ‘a’ is an object array) Basic customization: ndarray. Parameters version : int optional pickle version. ndarray. a += 3j is different than a = a + 3j: while they both perform the same computation. ‘F’..3))..7 Special methods For standard library functions: ndarray. a += 3 casts the result to fit back in a.1..) → a new object with type S. ndarray. for mixed precision calculations.) Returns either a new reference to self if dtype is not given or a new array static ndarray.) ndarray. . For pickling.__deepcopy__(() -> Deep copy of array. isfortran. For unpickling.. dtype.) Return a copy of the array. ‘A’}.

oct.__contains__(y) <==> y in x Conversion.__setslice__ x. They work only on arrays that have one element in them and return the appropriate scalar. y) <==> x[i]=y ndarray.__array_wrap__(obj) → Object of same type as ndarray object a.__len__() <==> len(x) ndarray. int. Array objects .__setitem__ x. long.__int__() <==> int(x) ndarray.__getslice__(i. copy otherwise.__setslice__(i.__getslice__(i.__setitem__(i.__oct__() <==> oct(x) 70 Chapter 1. j.__setitem__ ndarray.__oct__() <==> oct(x) ndarray.__contains__(y) <==> y in x ndarray. ndarray. ndarray.__contains__ x.__getitem__ ndarray.__getitem__ x.__contains__ x. j) <==> x[i:j] Use of negative indices is not supported. ndarray. Release 1. j) <==> x[i:j] x.__getitem__(y) <==> x[y] x.__len__() <==> len(x) ndarray. y) <==> x[i]=y x. 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.__getslice__ ndarray.1 ndarray.8.__array__(|dtype) → reference if type unchanged.__long__() <==> long(x) ndarray. and hex.__float__() <==> float(x) ndarray.__getitem__(y) <==> x[y] ndarray. y) <==> x[i:j]=y Use of negative indices is not supported.__setslice__ ndarray.__getslice__ x.__long__() <==> long(x) ndarray. float.__setitem__(i.__setslice__(i. j.NumPy Reference.__hex__() <==> hex(x) ndarray. the operations complex. Container customization: (see Indexing) ndarray. y) <==> x[i:j]=y x. ndarray.__float__() <==> float(x) ndarray.__int__() <==> int(x) ndarray.

complex128). 1.2. one floating-point type. Scalars 71 . however. Array scalars have the same attributes and methods as ndarrays.__hex__() <==> hex(x) String representations: ndarray. int8.complexfloating) will return True if val is a complex valued type. np. np. Use of the character codes. 1.__repr__() <==> repr(x) 1. np. 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. Array scalars live in a hierarchy (see the Figure below) of data types. In NumPy. Along with their (mostly) C-derived names.NumPy Reference. float. so none of the array scalar attributes are settable. Release 1. Two aliases (intp and uintp) pointing to the integer type that is sufficiently large to hold a C pointer are also provided.1 ndarray. what kind of array scalar is present can be determined using other members of the data type hierarchy. Thus. The C-like names are associated with character codes. which are shown in the table. This can be convenient in applications that don’t need to be concerned with all the ways data can be represented in a computer. is discouraged.). void).__repr__() <==> repr(x) ndarray. there are 24 new fundamental Python types to describe different types of scalars. unicode. float64.8. while isinstance(val.__str__() <==> str(x) ndarray. for example isinstance(val. smoothing out rough edges that result when mixing scalar and array operations.__str__() <==> str(x) ndarray. with several additional types compatible with Python’s types. Alternatively. more control is often needed.1 Built-in scalar types The built-in scalar types are shown below. isinstance(val. These type descriptors are mostly based on the types available in the C language that CPython is written in.2 Scalars Python defines only one type of a particular data class (there is only one integer type.generic) will return True if val is an array scalar object. etc. array scalars are immutable. For scientific computing. They can be detected using the hierarchy: For example. 1 This allows one to treat items of an array partly on the same footing as arrays. the integer.flexible) will return true if val is one of the flexible itemsize array types (string. Some 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 int_ float_ complex_ str_ unicode_ 1 Related Python type IntType (Python 2 only) FloatType ComplexType StringType UnicodeType However.2.g. however.

All the number types can be obtained using bit-width names as well. Release 1.1 Figure 1.8.2: Figure: Hierarchy of type objects representing the array data types.NumPy Reference. 72 Chapter 1. Array objects . Not shown are the two integer types intp and uintp which just point to the integer type that holds a pointer for the platform.

8.NumPy Reference. platform? means that the type may not be available on all platforms. In the tables below. and on the C-level the size of the actual bool data is not the same as a Python Boolean scalar. Tip: The default data type in Numpy is float_.2.1 The bool_ data type is very similar to the Python BooleanType but does not inherit from it because Python’s BooleanType does not allow itself to be inherited from. Compatibility with different C or Python types is indicated: two types are compatible if their data is of the same size and interpreted in the same way. Scalars 73 . Booleans: Type bool_ bool8 Remarks compatible: Python bool 8 bits Character code ’?’ Integers: byte short intc int_ longlong intp int8 int16 int32 int64 compatible: C char compatible: C short compatible: C int compatible: Python int compatible: C long long large enough to fit a pointer 8 bits 16 bits 32 bits 64 bits ’b’ ’h’ ’i’ ’l’ ’q’ ’p’ Unsigned integers: ubyte ushort uintc uint ulonglong uintp uint8 uint16 uint32 uint64 compatible: C unsigned char compatible: C unsigned short compatible: C unsigned int compatible: Python int compatible: C long long large enough to fit a pointer 8 bits 16 bits 32 bits 64 bits ’B’ ’H’ ’I’ ’L’ ’Q’ ’P’ Floating-point numbers: 1. Warning: The bool_ type is not a subclass of the int_ type (the bool_ is not even a number type). This is different than Python’s default implementation of bool as a sub-class of int. because type int is no longer a fixed-width integer type. Release 1. Warning: The int_ type does not inherit from the int built-in under Python 3.

you will need to change some of them to the new characters. arrays having dtype object_) are references to Python objects.0). They also do not (yet) have a ctypes attribute.shape generic. and u -> I. Otherwise.8. platform? 128 bits. platform? Any Python object: any Python object object_ ’O’ Note: The data actually stored in object arrays (i. but instead returns the actual object that the array item refers to. the needed changes are c -> S1.NumPy Reference.1 half single double float_ longfloat float16 float32 float64 float96 float128 compatible: C float compatible: C double compatible: Python float compatible: C long float 16 bits 32 bits 64 bits 96 bits. These changes make the type character convention more consistent with other Python modules such as the struct module. Array objects . w -> H.ndim 74 integer value of flags tuple of array dimensions tuple of bytes steps in each dimension number of array dimensions Continued on next page Chapter 1.flags generic.) str_ unicode_ void compatible: Python str compatible: Python unicode ’S#’ ’U#’ ’V#’ Warning: Numeric Compatibility: If you used old typecode characters in your Numeric code (which was never recommended). 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. object arrays behave more like usual Python lists. not the objects themselves. Release 1.000. s -> h. 1. 1 -> b..000.2 Attributes The array scalar objects have an array priority of NPY_SCALAR_PRIORITY (-1.2. in the sense that their contents need not be of the same Python type. Hence. The following data types are flexible. platform? ’e’ ’f’ ’d’ ’g’ Complex floating-point numbers: csingle complex_ clongfloat complex64 complex128 complex192 complex256 compatible: Python complex ’F’ ’D’ ’G’ two 32-bit floats two 64-bit floats two 96-bit floats. b -> B. In particular.e.strides generic. they share the same attributes as arrays: generic. The object type is also special because an array containing object_ items does not return an object_ object on item access. platform? two 128-bit floats.

Release 1.T transpose generic.flat a 1-d view of scalar generic.imag imaginary part of scalar generic. generic.size number of elements in the gentype generic.2.__array_struct__ Array protocol: struct generic.data pointer to start of data generic.__array_interface__ Array protocol: Python side generic.__array_wrap__ sc.ndim number of array dimensions generic.1 Table 1.dtype get array data-descriptor generic.data pointer to start of data generic.itemsize length of one element in bytes generic.dtype get array data-descriptor generic.base base object generic.NumPy Reference.itemsize length of one element in bytes generic.__array_interface__ Array protocol: Python side generic.real real part of scalar generic.base base object generic. Scalars 75 .T transpose generic.8.__array_struct__ Array protocol: struct 1.22 – continued from previous page generic.imag imaginary part of scalar generic.strides tuple of bytes steps in each dimension generic.flags integer value of flags generic.__array_wrap__(obj) return scalar from array generic.real real part of scalar generic.__array_priority__ Array priority.size number of elements in the gentype generic.shape tuple of array dimensions generic.flat a 1-d view of scalar generic.

NumPy Reference. so that the error state used for ufuncs also carries over to the math on array scalars. 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. sc. For consistency. despite many consequent attributes being either “get-only. math operations on array scalars are defined so that the same hardware flags are set and used to interpret the results as for ufunc. Attributes T base data dtype flags flat imag 76 transpose base object pointer to start of data get array data-descriptor integer value of flags a 1-d view of scalar imaginary part of scalar Continued on next page Chapter 1. • x[()] returns a 0-dimensional ndarray • x[’field-name’] returns the array scalar in the field field-name.__array_wrap__() sc.1 generic.3 Indexing See Also: Indexing.byteswap generic.__reduce__ generic.2.__array__ generic. (x can have fields.__array_wrap__ generic. exposes the same API as ndarray. In addition. This is the class from which it is strongly suggested users should derive custom scalar types. when it corresponds to a record data type. for example.” or completely irrelevant. The exceptions to the above rules are given below: generic generic.__array_wrap__(obj) return scalar from array 1.2. Release 1. Data type objects (dtype) Array scalars can be indexed like 0-dimensional arrays: if x is an array scalar.squeeze generic. Class from which most (all?) numpy scalar types are derived.__array_priority__ Array priority.__setstate__ generic.4 Methods Array scalars have exactly the same methods as arrays. Array objects .) 1.generic Base class for numpy scalar types.setflags Base class for numpy scalar types. generic.__array_wrap__(obj) return scalar from array Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) class numpy.8.__array__(|type) return 0-dim array sc.

shape tuple of array dimensions generic.base base object generic.24 – continued from previous page itemsize length of one element in bytes nbytes length of item in bytes ndim number of array dimensions real real part of scalar shape tuple of array dimensions size number of elements in the gentype strides tuple of bytes steps in each dimension generic.NumPy Reference.real real part of scalar generic.1 Table 1. Release 1.flat a 1-d view of scalar generic.strides tuple of bytes steps in each dimension Methods all any argmax argmin argsort 1.ndim number of array dimensions generic.imag imaginary part of scalar generic. Scalars Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Continued on next page 77 .flags integer value of flags generic.size number of elements in the gentype generic.8.dtype get array data-descriptor generic.data pointer to start of data generic.2.itemsize length of one element in bytes generic.T transpose generic.nbytes length of item in bytes generic.

8. Array objects .NumPy Reference.25 – continued from previous page astype Not implemented (virtual attribute) byteswap Not implemented (virtual attribute) choose Not implemented (virtual attribute) clip Not implemented (virtual attribute) compress Not implemented (virtual attribute) conj conjugate Not implemented (virtual attribute) copy Not implemented (virtual attribute) cumprod Not implemented (virtual attribute) cumsum Not implemented (virtual attribute) diagonal Not implemented (virtual attribute) dump Not implemented (virtual attribute) dumps Not implemented (virtual attribute) fill Not implemented (virtual attribute) flatten Not implemented (virtual attribute) getfield Not implemented (virtual attribute) item Not implemented (virtual attribute) itemset Not implemented (virtual attribute) max Not implemented (virtual attribute) mean Not implemented (virtual attribute) min Not implemented (virtual attribute) newbyteorder([new_order]) Return a new dtype with a different byte order.all() Not implemented (virtual attribute) 78 Chapter 1. Release 1.1 Table 1. nonzero Not implemented (virtual attribute) prod Not implemented (virtual attribute) ptp Not implemented (virtual attribute) put Not implemented (virtual attribute) ravel Not implemented (virtual attribute) repeat Not implemented (virtual attribute) reshape Not implemented (virtual attribute) resize Not implemented (virtual attribute) round Not implemented (virtual attribute) searchsorted Not implemented (virtual attribute) setfield Not implemented (virtual attribute) setflags Not implemented (virtual attribute) sort Not implemented (virtual attribute) squeeze Not implemented (virtual attribute) std Not implemented (virtual attribute) sum Not implemented (virtual attribute) swapaxes Not implemented (virtual attribute) take Not implemented (virtual attribute) tofile Not implemented (virtual attribute) tolist Not implemented (virtual attribute) tostring Not implemented (virtual attribute) trace Not implemented (virtual attribute) transpose Not implemented (virtual attribute) var Not implemented (virtual attribute) view Not implemented (virtual attribute) generic.

See Also: The generic. See Also: The generic.argmax() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented.2. Release 1. all the attributes of the ndarray class so as to provide a uniform API.NumPy Reference.astype() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. Scalars 79 . See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented.8. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API.any() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented.1 Class generic exists solely to derive numpy scalars from. and possesses. all the attributes of the ndarray class so as to provide a uniform API. and possesses. See Also: The generic. See Also: The 1. albeit unimplemented. and possesses.argmin() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. and possesses. See Also: The generic.byteswap() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.argsort() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. See Also: The generic. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API.

Array objects . See Also: The generic. See Also: The generic. See Also: The generic.8. and possesses.NumPy Reference. all the attributes of the ndarray class so as to provide a uniform API.clip() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. See Also: The generic.conj() generic. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API.compress() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.cumprod() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented. albeit unimplemented. albeit unimplemented. and possesses. and possesses.conjugate() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. albeit unimplemented. See Also: The generic.1 generic. and possesses.choose() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.copy() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented. Release 1. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. See Also: The generic. and possesses.cumsum() Not implemented (virtual attribute) 80 Chapter 1.

See Also: The generic.getfield() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented.1 Class generic exists solely to derive numpy scalars from. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API.dump() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.diagonal() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. and possesses.fill() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic. albeit unimplemented. See Also: The generic.2. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. See Also: The generic.8. albeit unimplemented.dumps() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented. See Also: The generic. albeit unimplemented. Scalars 81 .NumPy Reference. all the attributes of the ndarray class so as to provide a uniform API. and possesses. and possesses.flatten() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The 1. Release 1. and possesses. albeit unimplemented. and possesses. and possesses. all the attributes of the ndarray class so as to provide a uniform API. and possesses.

Changes are also made in all fields and sub-arrays of the data type. all the attributes of the ndarray class so as to provide a uniform API.little endian •{‘>’. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API.item() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses.big endian •{‘=’. ‘L’} . and possesses. albeit unimplemented. See Also: The generic.NumPy Reference. ‘I’} . See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API. ‘N’} .swap dtype from current to opposite endian •{‘|’. all the attributes of the ndarray class so as to provide a uniform API.itemset() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic. and possesses.newbyteorder(new_order=’S’) Return a new dtype with a different byte order. See Also: The generic.native order •‘S’ . and possesses.max() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.mean() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.1 generic. albeit unimplemented.8. albeit unimplemented. Release 1.min() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. ‘B’} . The new_order code can be any from the following: •{‘<’. albeit unimplemented. and possesses. See Also: The generic.ignore (no change to byte order) 82 Chapter 1. Array objects .

The code does a case-insensitive check on the first letter of new_order for the alternatives above.8. generic.put() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.nonzero() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented. See Also: The generic. See Also: The generic. See Also: The generic.ravel() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. Returns new_dtype : dtype New dtype object with the given change to the byte order.ptp() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses.1 Parameters new_order : str. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. and possesses. optional Byte order to force. any of ‘B’ or ‘b’ or ‘biggish’ are valid to specify big-endian.2. albeit unimplemented. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API.NumPy Reference. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented. Release 1. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. The default value (‘S’) results in swapping the current byte order. Scalars 83 . and possesses.prod() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic.repeat() Not implemented (virtual attribute) 1. For example. a value from the byte order specifications above.

all the attributes of the ndarray class so as to provide a uniform API.reshape() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API.setfield() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. and possesses.setflags() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic. See Also: The generic. Release 1. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. and possesses.8. and possesses. See Also: The generic.resize() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. albeit unimplemented. albeit unimplemented. See Also: The generic. albeit unimplemented. and possesses. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API.NumPy Reference. See Also: The 84 Chapter 1. Array objects .round() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic.searchsorted() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.1 Class generic exists solely to derive numpy scalars from. albeit unimplemented. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented.

2. and possesses. See Also: The generic. albeit unimplemented. See Also: 1. and possesses. See Also: The generic. albeit unimplemented. Release 1. Scalars 85 . See Also: The generic.tofile() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.1 generic. See Also: The generic. albeit unimplemented.squeeze() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented.swapaxes() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses.NumPy Reference.std() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented.sort() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.sum() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. See Also: The generic. and possesses.8.take() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.

NumPy Reference. See Also: The generic.__array__(|type) return 0-dim array generic. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented.transpose() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.trace() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. Array objects .__array__() sc. albeit unimplemented.__array_wrap__(obj) return scalar from array 86 Chapter 1. albeit unimplemented. and possesses. and possesses. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. and possesses. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API.tostring() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic. all the attributes of the ndarray class so as to provide a uniform API.8. and possesses. and possesses. See Also: The generic. albeit unimplemented.tolist() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.var() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. Release 1.__array_wrap__() sc.1 The generic.view() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The generic.

3. (b) what is the data-type of each field. albeit unimplemented. an aggregate of other data types. See Also: The 1. and register it with NumPy. This will work to a degree.byteswap() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. using the Numpy C-API.5 Defining new types 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. albeit unimplemented. It describes the following aspects of the data: 1. and possesses. float. Release 1. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. Python object. but internally certain behaviors are fixed by the data type of the array. and 1. all the attributes of the ndarray class so as to provide a uniform API.NumPy Reference. and possesses.3 Data type objects (dtype) A data type object (an instance of numpy.setflags() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. Type of the data (integer.squeeze() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented.1 generic. Such new types can only be defined in C. To fully customize the data type of an array you need to define a new data-type. etc. (a) what are the names of the “fields” of the record.8. describing an array item consisting of an integer and a float). Data type objects (dtype) 87 .dtype class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. by which they can be accessed.__setstate__() generic. (e. See Also: The generic.2.) 2.g.g. 1. If the data type is a record. the integer) 3.. Byte order of the data (little-endian or big-endian) 4. and possesses. See Also: The generic. Size of the data (how many bytes is in e.__reduce__() generic.

NumPy Reference. Sub-arrays always have a C-contiguous memory layout. 7. (2.name ’int32’ >>> dt. the dimensions of the sub-array are appended to the shape of the array when the array is created.0. etc. If the data type is a sub-array. 7. a data type can describe items that are themselves arrays of items of another data type. The parent data type should be of sufficient size to contain all its fields. (’John’. Struct data types are formed by creating a data type whose fields contain other data types.0. np.1 (c) which part of the memory block each field takes.0))].0]) >>> x[1][’grades’] array([ 6..dtype(’>i4’) >>> dt. e. be of a fixed size.))) Items of an array of this data type are wrapped in an array scalar type that also has two fields: >>> x = np.0. (6. 16). Finally. however. Example A simple data type containing a 32-bit big-endian integer: (see Specifying and constructing data types for details on construction) >>> dt = np. Each field has a name by which it can be accessed.str_. even though they can be used in place of one whenever a data type specification is needed in Numpy. These sub-arrays must.8..))]) >>> dt[’name’] dtype(’|S16’) >>> dt[’grades’] dtype((’float64’. np. by indexing. Example A record data type containing a 16-character string (in field ‘name’) and a sub-array of two 64-bit floating-point number (in field ‘grades’): >>> dt = np. will be a Python object whose type is the scalar type associated with the data type of the array. dtype=dt) >>> x[1] (’John’. If an array is created using a data-type describing a sub-array. Array objects .g. 7.0)).itemsize 4 >>> dt.]) >>> type(x[1]) 88 Chapter 1. floating-point numbers. what is its shape and data type. Struct data types may also contain nested struct sub-array data types in their fields. there are several built-in scalar types in Numpy for various precision of integers.float64.type is np.dtype([(’name’. (’grades’. (8. An item extracted from an array. 7.array([(’Sarah’. 5. Release 1. Sub-arrays in a field of a record behave differently. [6.int32 True The corresponding array scalar type is int32. see Record Access. Note that the scalar types are not dtype objects.byteorder ’>’ >>> dt. the parent is nearly always based on the void type which allows an arbitrary item size. To describe the type of scalar data.(2.

void’> >>> type(x[1][’grades’]) <type ’numpy. containing int16: >>> np. copy : bool. [(’f1’. and contains elements described by a dtype object.1 Specifying and constructing data types Whenever a data-type is required in a NumPy function or method. [(’f1’. A numpy array is homogeneous.ndarray’> 1.3. ’<i4’)]) 1. one field named ‘f1’.8. align : bool. np. np. If a struct dtype is being created. Release 1. optional Make a new copy of the data-type object. (’f2’. ’<i2’)])]) Record.int32)]) dtype([(’f1’. If False. ’<u4’). two fields: the first field contains an unsigned int.dtype(np.dtype Create a data type object.NumPy Reference. ’<i2’)]) Record.int16)])]) dtype([(’f1’. class numpy. np. Can be True only if obj is a dictionary or a comma-separated string. the second an int32: >>> np.1 <type ’numpy. one field name ‘f1’. the result may just be a reference to a built-in data-type object. See Also: result_type Examples Using array-scalar type: >>> np. Parameters obj Object to be converted to a data type object. A dtype object can be constructed from different combinations of fundamental numeric types.dtype([(’f1’. either a dtype object or something that can be converted to one can be supplied. Data type objects (dtype) 89 .int16)]) dtype([(’f1’. (’f2’.3.dtype([(’f1’. Such conversions are done by the dtype constructor: dtype Create a data type object. optional Add padding to the fields to match what a C compiler would output for a similar Cstruct. this also sets a sticky alignment flag isalignedstruct. in itself containing a record with one field: >>> np.uint).dtype([(’f1’.int16) dtype(’int16’) Record. np.

void. ’|V10’)]) Subdivide int16 into 2 int8‘s.1)})) dtype((’<i2’.uint8.fields Dictionary of named fields defined for this data type.dtype([(’hello’. called x and y.’S10’)]) dtype([(’a’.1 Using array-protocol type strings: >>> np.dtype({’surname’:(’S25’. 0 and 1 are the offsets in bytes: >>> np. or None if there are no fields. ’<f8’.base dtype. ’|S1’). ’|i1’).10)]) dtype([(’hello’. Two fields named ‘gender’ and ‘age’: >>> np. The array-protocol typestring of this data-type object. or None. The format is that required by the ‘descr’ key in the __array_interface__ attribute. Dictionary of named fields defined for this data type. Tuple (item_dtype.uint8]}) dtype([(’gender’.3)). int is a fixed type. [(’x’.0).dtype("i4.25)}) dtype([(’surname’. void is a flexible type. here of size 10: >>> np. ’<f8’). ’y’:(np. (’age’.np. The dictionary is indexed by keys that are the names of the fields. {’x’:(np.0). Each entry in the dictionary is a tuple 90 Chapter 1. (’age’.int8.int8. Array objects .’age’:(np. (’f1’. The shape is (2. Boolean indicating whether the dtype is a struct which maintains field alignment. Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. or None.(np. and dtype. Integer indicating how this dtype relates to the built-in dtypes.NumPy Reference. Boolean indicating whether the byte order of this dtype is native A bit-width name for this data-type. ’|i1’)])) Using dictionaries. 3 the field’s shape. here 0 and 25: >>> np.np.(’b’. 3). ’<i4’). (2. ’|u1’)]) Attributes base descr fields hasobject isalignedstruct isbuiltin isnative metadata name names shape str subdtype Array-interface compliant full description of the data-type.descr Array-interface compliant full description of the data-type.3): >>> np. (2. Ordered list of field names.3)f8") dtype([(’f0’. ’|S25’).int. dtype.dtype({’names’:[’gender’.dtype([(’a’. ’<i4’. 3))]) Using tuples. (’b’.’f8’).8. ’|S10’)]) Using comma-separated field formats. Release 1.int16.’age’]. (’world’. Shape tuple of the sub-array if this data type describes a sub-array. (’y’. ’formats’:[’S1’. ’|u1’)]) Offsets in bytes.dtype((np.(’world’. shape) if this dtype describes a sub-array.

16). with fields if this is a dtype compiled into numpy (such as ints. 0)} dtype.getfield.isbuiltin dt = np. so when combining multiple structs together. (’grades’. 0 1 2 if this is a structured array type. Data type objects (dtype) 91 .))]) >>> print dt.isalignedstruct Boolean indicating whether the dtype is a struct which maintains field alignment. 16). otherwise it’s meta-data). and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won’t.metadata dtype.8.name A bit-width name for this data-type. 1.isbuiltin dtype.isnative Boolean indicating whether the byte order of this dtype is native to the platform.hasobject Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. See user. dtype. floats etc) 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. np.setfield methods.dtype(’i2’) dt. ’f8’)]) dt. ’name’: (dtype(’|S16’).dtype([(’field1’. 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. Un-sized flexible data-type objects do not have this attribute.))).setfield Examples >>> dt = np. dtype. it is preserved and produces new dtypes which are also aligned. Read-only. Notice also that the first two elements of the tuple can be passed directly as arguments to the ndarray. np. dtype. title]) If present.NumPy Reference. Special handling may be required. Release 1.1 fully describing the field: (dtype.str_.(2.fields {’grades’: (dtype((’float64’.isbuiltin dt = np.dtype([(’name’. See Also: ndarray. (2. ndarray.dtype(’f8’) dt. This flag is sticky.getfield and ndarray.isbuiltin Integer indicating how this dtype relates to the built-in dtypes. Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer).float64.3. offset[. Examples >>> >>> 1 >>> >>> 1 >>> >>> 0 dt = np.user-defined-data-types in the Numpy manual.

and item_dtype the data type of the array.dtype([(’name’. dtype. The default value (‘S’) results in swapping the current byte order. The shape is the fixed shape of the sub-array described by this data type. (’grades’. or None if there are no fields. Examples >>> dt = np.little endian . 16). optional Byte order to force. and None otherwise. shape) if this dtype describes a sub-array. Notes Changes are also made in all fields and sub-arrays of the data type. This can be used.big endian .newbyteorder(new_order=’S’) Return a new dtype with a different byte order. For example.subdtype Tuple (item_dtype. {’>’.str_. {’|’. for example.str The array-protocol typestring of this data-type object. np.8.names Ordered list of field names. and () otherwise. The names are ordered according to increasing byte offset. If a field whose dtype object has this attribute is retrieved. Array objects .shape Shape tuple of the sub-array if this data type describes a sub-array. Parameters new_order : string. any of ‘>’ or ‘B’ or ‘b’ or ‘brian’ are valid to specify big-endian. to walk through all of the named fields in offset order. then the extra dimensions implied by shape are tacked on to the end of the retrieved array. swap ’L’} ’B’} ’N’} ’I’} dtype from current to opposite endian . dtype. new_order codes can be any of: * * * * * ’S’ {’<’. Release 1. ’grades’) dtype. dtype.1 dtype. Changes are also made in all fields and sub-arrays of the data type. np.float64.ignore (no change to byte order) The code does a case-insensitive check on the first letter of new_order for these alternatives.native order . 92 Chapter 1. Returns new_dtype : dtype New dtype object with the given change to the byte order. Methods newbyteorder([new_order]) Return a new dtype with a different byte order.NumPy Reference. {’=’. a value from the byte order specifications below. (2.))]) >>> dt.names (’name’.

3.int32) # 32-bit integer >>> dt = np. This is true for their sub-classes as well. Data type objects (dtype) 93 .newbyteorder(’>’) True >>> np. Note that not all data-type information can be supplied with a type-object: for example.newbyteorder(’S’) True >>> native_dt == swapped_dt.dtype(np. Release 1.NumPy Reference.newbyteorder(’L’) True >>> np.newbyteorder(’<’) True >>> np. Example >>> dt = np.dtype(swapped_code+’i2’) >>> native_dt.dtype(’>i2’) == native_dt. Array-scalar types The 24 built-in array scalar type objects all convert to an associated data-type object.newbyteorder(’B’) True What can be converted to a data-type object is described below: dtype object Used as-is.dtype(native_code+’i2’) >>> swapped_dt = np.newbyteorder(’S’) == swapped_dt True >>> native_dt.dtype(’<i2’) == native_dt.newbyteorder() == swapped_dt True >>> native_dt == swapped_dt.8. and require an explicitly given size to be useful.dtype(’<i2’) == native_dt.newbyteorder(’=’) True >>> native_dt == swapped_dt.1 Examples >>> import sys >>> sys_is_le = sys.dtype(np.byteorder == ’little’ >>> native_code = sys_is_le and ’<’ or ’>’ >>> swapped_code = sys_is_le and ’>’ or ’<’ >>> native_dt = np. None The default data type: float_.newbyteorder(’N’) True >>> native_dt == native_dt.dtype(’>i2’) == native_dt. flexible data-types have a default itemsize of 0.complex128) # 128-bit complex floating-point number Generic types The generic hierarchical type objects convert to corresponding type objects according to the associations: 1.newbyteorder(’|’) True >>> np.

The attribute must return something that is convertible into a dtype object.dtype(’b’) np. signedinteger unsignedinteger character generic.dtype Any type object with a dtype attribute: The attribute will be accessed and used directly.dtype(’<f’) np.dtype(float) >>> dt = np.1 number. or ’=’ (hardware-native. native byte order big-endian unsigned short little-endian single-precision float double-precision floating-point number Array-protocol type strings (see The Array Interface) The first character specifies the kind of data and the remaining characters specify how many bytes of data.dtype(object) # Python-compatible floating-point number # Python-compatible integer # Python object Types with . Several kinds of strings can be converted.dtype(’>H’) np. to specify the byte order. ’<’ (littleendian).8.dtype(’d’) # # # # byte. flexible float cfloat int_ uint string void Built-in Python types Several python types are equivalent to a corresponding array scalar when used to generate a dtype object: int bool float complex str unicode buffer (all others) int_ bool_ float_ cfloat string unicode_ void object_ Example >>> dt = np. Recognized strings can be prepended with ’>’ (big-endian).dtype(int) >>> dt = np. that uniquely identifies it. the default). floating complexfloating integer. Release 1. ’a’ ’U’ ’V’ 94 Boolean (signed) integer unsigned integer floating-point complex-floating point string unicode raw data (void) Chapter 1. One-character strings Each built-in data-type has a character code (the updated Numeric typecodes). Array objects . inexact. Example >>> >>> >>> >>> dt dt dt dt = = = = np. The supported kinds are ’b’ ’i’ ’u’ ’f’ ’c’ ’S’.NumPy Reference.

10)) >>> dt = np.dtype((void. If the optional shape specifier is provided.dtype(’f8’) np. Release 1..keys(): Example >>> dt = np.3.4)a10") Type strings Any string in numpy.dtype((’U’. 10)) 1.dtype("i4. Example • field named f0 containing a 32-bit integer • field named f1 containing a 2 x 3 sub-array of 64-bit floating-point numbers • field named f2 containing a 32-bit floating-point number >>> dt = np. ’f1’. (3.8.sctypeDict..3)f8.dtype(’a25’) # # # # 32-bit signed integer 64-bit floating-point number 128-bit complex floating-point number 25-character string String with comma-separated fields Numarray introduced a short-hand notation for specifying the format of a record as a comma-separated string of basic formats. ’f<N-1>’ where N (>1) is the number of comma-separated basic formats in the string.dtype(’c16’) np.) containing 64-bit unsigned integers • field named f2 containing a 3 x 4 sub-array containing 10-character strings >>> dt = np. The generated data-type fields are named ’f0’. NumPy allows a modification on the format in that any string that can uniquely identify the type can be used to specify the data-type in a field.1 Example >>> >>> >>> >>> dt dt dt dt = = = = np.dtype(’i4’) np.dtype((str. Example >>> dt = np. (2.dtype(’uint32’) >>> dt = np.NumPy Reference. the second argument is an integer providing the desired itemsize. Data type objects (dtype) # 10-byte wide data block # 35-character string # 10-character unicode string 95 . 3u8. 35)) >>> dt = np.. itemsize) The first argument must be an object that is converted to a zero-sized flexible data-type object. then the data-type for the corresponding field describes a sub-array.dtype(’Float64’) # 32-bit unsigned integer # 64-bit floating-point number (flexible_dtype.dtype("a3. Parenthesis are required on the shape if it has more than one dimension. . f4") • field named f0 containing a 3-character string • field named f1 containing a sub-array of shape (3. A basic format in this context is an optional shape specifier followed by an array-protocol type string.

each being an unsigned 8-bit integer: >>> dt = np.3)f8.’u1’). If the dtype being constructed is aligned. The itemsize key allows the total size of the dtype to be set. is assigned). 1)) # 10-character string >>> dt = np.’u1’). Note that a 3-tuple with a third argument equal to 1 is equivalent to a 2-tuple. ’offsets’: .3))) # 2 x 3 record sub-array [(field_name. is the field name (if this is ” then a standard field name. B. The optional third element field_shape contains the shape if this field represents an array of the data-type in the second element. shape) The first argument is any object that can be converted into a fixed-size data-type object. The titles can be any string or unicode object and will add another entry to the fields dictionary keyed by the title and referencing the same field tuple which will contain the title as an additional tuple member. and must be an integer large enough so all the fields are within the dtype. Array objects .. their values must each be lists of the same length as the names and formats lists... G. (’A’. (2.int32. field_dtype.. (’B’.dtype((’S10’. then the data-type object is equivalent to fixed dtype.NumPy Reference.dtype((’i4.’u1’). field_dtype.] obj should be a list of fields where each field is described by a tuple of length 2 or 3. A.2))) # 2 x 2 integer sub-array >>> dt = np. can be anything that can be interpreted as a data-type. field_shape). ’<i4’)]) Data-type with fields R. field_name. ’>i4’).dtype((np. This style does not accept align in the dtype constructor as it is assumed that all of the memory is accounted for by the array interface description.} . then the new dtype defines a sub-array of the given shape. (’little’. the itemsize must also be divisible by the struct alignment. Example 96 Chapter 1. ’itemsize’: This style has two required and three optional keys. (Equivalent to the descr item in the __array_interface__ attribute.1 (fixed_dtype. . The second argument is the desired shape of this type. If the shape parameter is 1.. Release 1. Example Data-type with fields big (big-endian 32-bit integer) and little (little-endian 32-bit integer): >>> dt = np.dtype([(’R’. The field names must be strings and the field formats can be any object accepted by dtype constructor. The names and formats keys are required. ’f#’. (’G’.) The first element. ’formats’: .....dtype([(’big’. Example >>> dt = np..... while the titles value is a list of titles for each field (None can be used if no title is desired for that field). (2.. When the optional keys offsets and titles are provided.’u1’)]) {’names’: . f4’. Their respective values are equal-length lists with the field names and the field formats.8.. and the second string is the “name” which must be a valid Python identifier. The field name may also be a 2-tuple of strings where the first string is either a “title” (which may be any string or unicode string) or meta-data for the field which can be any object. The offsets value is a list of byte offsets (integers) for each field. (2. If shape is a tuple. The second element.. ’titles’: .

. 4))) 32-bit integer. ’formats’: [uint8. uint8. both being 8-bit unsigned integers. The union mechanism is preferred. This is how you could assign named fields to any built-in datatype object. functioning like the ‘union’ type in C. .3. In NumPy 1. Data type objects (dtype) 97 . g..8.. Both arguments must be convertible to data-type objects in this case.’b’].(’b’. .int16. new_dtype) This usage is discouraged.NumPy Reference.dtype({’col1’: (’S10’.dtype({’names’: [’r’..dtype((np..’a’]. 0).1 Data type with fields r. .int16. 10).dtype((’i4’. obj should contain string or unicode keys that refer to (data-type.(’g’. and col3 (integers at byte position 14): >>> dt = np. each being a 8-bit unsigned integer: >>> dt = np.’u1’). ’u1’].(’a’. (np. a. whose first two bytes are interpreted as an integer via field real. b. 1. ’titles’: [’Red pixel’. col2 (32-bit float at byte position 10).3.. the first at byte position 0 from the start of the field and the second at position 2: >>> dt = np. ’Blue pixel’]}) {’field1’: . Example Data type containing field col1 (10-character string at byte position 0)..{’real’:(np. 14)}) (base_dtype. Example 32-bit integer. >>> dt = np.dtype({’names’: [’r’. This style allows passing in the fields attribute of a data-type object. 2]. offset) or (data-type.dtype((np.’u1’). because it is ambiguous with the other dict-based construction method.’u1’).. ’col3’: (int.int32. title) tuples.. g.int32. [(’r’. a that interpret the 4 bytes in the integer as four unsigned integers: >>> dt = np. uint8]}) Data type with fields r and b (with the given titles). ’formats’: [’u1’. and the following two bytes via field imag.} This usage is discouraged. Release 1..2 dtype Numpy data type descriptions are instances of the dtype class. If you have a field called ‘names’ and a field called ‘formats’ there will be a conflict. offset. .) containing 8-bit integers: >>> dt = np. ’col2’: (float32.. b. which is interpreted as consisting of a sub-array of shape (4. uint8. The base_dtype is the data-type object that the new data-type builds on. 0)..’imag’:(np.’b’.. containing fields r.. ’offsets’: [0. it is possible to specify struct dtypes with overlapping fields. ’field2’: .int8. 2)}) 32-bit integer.’u1’)])) 1.’g’.7 and later.

char dtype. The array-protocol typestring of this data-type object.1 Attributes The type of the data is described by the following dtype attributes: dtype. dtype. dtype. Array objects .name A bit-width name for this data-type. dtype.char A unique character code for each of the 21 different built-in types.kind A character code (one of ‘biufcSUV’) identifying the general kind of data. Endianness of this data: dtype. 98 Chapter 1. Size of the data is in turn described by: dtype. dtype.byteorder A character indicating the byte-order of this data-type object.num A unique number for each of the 21 different built-in types.itemsize A bit-width name for this data-type.byteorder A character indicating the byte-order of this data-type object. The element size of this data-type object. For the flexible data-types.NumPy Reference. dtype.num dtype. One of: ‘=’ ‘<’ ‘>’ ‘|’ native little-endian big-endian not applicable All built-in data-type objects have byteorder either ‘=’ or ‘|’. A unique number for each of the 21 different built-in types. dtype. Release 1. A character code (one of ‘biufcSUV’) identifying the general kind of data.str The array-protocol typestring of this data-type object.8. dtype.itemsize The element size of this data-type object.name dtype. These are roughly ordered from least-to-most precision.kind dtype.type dtype. For 18 of the 21 types this number is fixed by the data-type. dtype. this number can be anything.type The type object used to instantiate a scalar of this data-type. Un-sized flexible data-type objects do not have this attribute. A unique character code for each of the 21 different built-in types.str The type object used to instantiate a scalar of this data-type.

dtype(native_code + ’i2’) >>> dt.byteorder ’|’ >>> # Even if specific code is given. otherwise it’s meta-data). dtype.))).byteorder ’|’ >>> # or ASCII strings >>> np. 16). This can be used.dtype(’S2’). 16).3. or None if there are no fields.dtype([(’name’. 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.fields {’grades’: (dtype((’float64’. The names are ordered according to increasing byte offset.dtype(’i2’) >>> dt. 0)} dtype.))]) >>> print dt. title]) If present. and it is native >>> # ’=’ is the byteorder >>> import sys >>> sys_is_le = sys. Each entry in the dictionary is a tuple fully describing the field: (dtype. Ordered list of field names. or None if there are no fields. See Also: ndarray.setfield methods.float64.1 Examples >>> dt = np.byteorder ’=’ >>> # Swapped code shows up as itself >>> dt = np. (’grades’. offset[.byteorder == swapped_code True Information about sub-data-types in a record: dtype. Notice also that the first two elements of the tuple can be passed directly as arguments to the ndarray.setfield Examples >>> dt = np.byteorder ’=’ >>> # endian is not relevant for 8 bit numbers >>> np. or None.str_. Data type objects (dtype) 99 .fields dtype. to walk through all of the named fields in offset order. np.(2. np.names Dictionary of named fields defined for this data type. 1. (2. ’name’: (dtype(’|S16’).names Ordered list of field names. or None.NumPy Reference.8.fields Dictionary of named fields defined for this data type. Release 1.getfield. for example. The dictionary is indexed by keys that are the names of the fields.dtype(’i1’).getfield and ndarray.byteorder == ’little’ >>> native_code = sys_is_le and ’<’ or ’>’ >>> swapped_code = sys_is_le and ’>’ or ’<’ >>> dt = np. ndarray.dtype(swapped_code + ’i2’) >>> dt.

with fields if this is a dtype compiled into numpy (such as ints.names (’name’.NumPy Reference. The shape is the fixed shape of the sub-array described by this data type. ’grades’) For data types that describe sub-arrays: dtype. and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won’t. Array objects .))]) >>> dt. dtype. 0 1 2 100 if this is a structured array type. dtype.hasobject Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. USE_SETITEM.shape Shape tuple of the sub-array if this data type describes a sub-array.descr dtype. dtype.1 Examples >>> dt = np. and item_dtype the data type of the array.flags Bit-flags describing how this data type is to be interpreted. shape) if this dtype describes a sub-array. LIST_PICKLE. and Shape tuple of the sub-array if this data type describes a sub-array.str_.isbuiltin Integer indicating how this dtype relates to the built-in dtypes. ITEM_IS_POINTER. floats etc) 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. Attributes providing additional information: dtype.float64. Bit-flags describing how this data type is to be interpreted. A full explanation of these flags is in C-API documentation.isbuiltin dtype. 16). then the extra dimensions implied by shape are tacked on to the end of the retrieved array. Boolean indicating whether the byte order of this dtype is native Array-interface compliant full description of the data-type. Special handling may be required. Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). np. (2.multiarray as the constants ITEM_HASOBJECT. and () otherwise.alignment Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes. If a field whose dtype object has this attribute is retrieved. NEEDS_PYAPI. (’grades’. See user.subdtype dtype.core. and None otherwise.user-defined-data-types in the Numpy manual.subdtype Tuple (item_dtype. Chapter 1. dtype. Integer indicating how this dtype relates to the built-in dtypes.isnative dtype.dtype([(’name’.flags dtype. The required alignment (bytes) of this data-type according to the compiler. Release 1. shape) if this dtype describes a sub-array. np.8. Read-only. dtype.shape Tuple (item_dtype. Bit-masks are in numpy. USE_GETITEM.hasobject dtype. they are largely useful for user-defined data-types. NEEDS_INIT.

The format is that required by the ‘descr’ key in the __array_interface__ attribute.1 Examples >>> >>> 1 >>> >>> 1 >>> >>> 0 dt = np. dtype. dtype.ignore (no change to byte order) The code does a case-insensitive check on the first letter of new_order for these alternatives.dtype([(’field1’. Parameters new_order : string. {’|’.native order .dtype(’f8’) dt. The default value (‘S’) results in swapping the current byte order.newbyteorder([new_order]) Return a new dtype with a different byte order. ’f8’)]) dt. Methods Data types have the following method for changing the byte order: dtype. More information is available in the C-API section of the manual. {’>’. {’=’. swap ’L’} ’B’} ’N’} ’I’} dtype from current to opposite endian . 1.descr Array-interface compliant full description of the data-type.newbyteorder(new_order=’S’) Return a new dtype with a different byte order.8.isnative Boolean indicating whether the byte order of this dtype is native to the platform. Notes Changes are also made in all fields and sub-arrays of the data type. optional Byte order to force.isbuiltin dt = np.NumPy Reference. Release 1. new_order codes can be any of: * * * * * ’S’ {’<’. Data type objects (dtype) 101 . a value from the byte order specifications below. For example.isbuiltin dtype.alignment The required alignment (bytes) of this data-type according to the compiler.3. Changes are also made in all fields and sub-arrays of the data type.big endian . any of ‘>’ or ‘B’ or ‘b’ or ‘brian’ are valid to specify big-endian. dtype.little endian .isbuiltin dt = np.dtype(’i2’) dt. Returns new_dtype : dtype New dtype object with the given change to the byte order.

or a tuple of slice objects and 102 Chapter 1.__reduce__ dtype.newbyteorder(’=’) True >>> native_dt == swapped_dt.. advanced indexing. an integer. .. Which one occurs depends on obj. where x is the array and obj the selection. There are three kinds of indexing available: record access.newbyteorder(’N’) True >>> native_dt == native_dt. expN].dtype(native_code+’i2’) >>> swapped_dt = np.. the latter is just syntactic sugar for the former. 1.newbyteorder(’B’) True The following methods implement the pickle protocol: dtype.__reduce__() dtype. exp2.dtype(’<i2’) == native_dt..8.newbyteorder(’S’) == swapped_dt True >>> native_dt. Array objects .newbyteorder(’>’) True >>> np.dtype(’>i2’) == native_dt.dtype(’>i2’) == native_dt. x[(exp1.NumPy Reference.dtype(’<i2’) == native_dt..newbyteorder(’<’) True >>> np.dtype(swapped_code+’i2’) >>> native_dt.newbyteorder(’S’) True >>> native_dt == swapped_dt.4.1 Examples >>> import sys >>> sys_is_le = sys. expN)] is equivalent to x[exp1..newbyteorder(’|’) True >>> np.1 Basic Slicing Basic slicing extends Python’s basic concept of slicing to N dimensions.newbyteorder(’L’) True >>> np.newbyteorder() == swapped_dt True >>> native_dt == swapped_dt. Release 1. Basic slicing occurs when obj is a slice object (constructed by start:stop:step notation inside of brackets).__setstate__ dtype. . basic slicing.byteorder == ’little’ >>> native_code = sys_is_le and ’<’ or ’>’ >>> swapped_code = sys_is_le and ’>’ or ’<’ >>> native_dt = np.__setstate__() 1. Note: In Python. exp2.4 Indexing ndarrays can be indexed using the standard Python x[obj] syntax.

the valid range is 0 ≤ ni < di where di is the i-th element of the shape of the array. i + k. [[4]. and k is the step (k 6= 0). 3. As in Python. the Ellipsis object.[3]]. The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index). Then. Example >>> x = np.i = q k + r. Negative k makes stepping go towards smaller indices. 5]) • Negative i and j are interpreted as n + i and n + j where n is the number of elements in the corresponding dimension. If k is not given it defaults to 1. 5. so that i + (m .1) k < j. 4]) • Assume n is the number of elements in the dimension being sliced. Ellipsis and newaxis objects can be interspersed with these as well. i + (m . 9]) >>> x[-3:3:-1] array([7. 6. then : is assumed for any subsequent dimensions.array([0. Note that :: is the same as : and means select all indices along this axis. All arrays generated by basic slicing are always views of the original array.. Negative indices are interpreted as counting from the end of the array (i. 7. Example >>> x = np. if i < 0. 6.array([[[1].NumPy Reference. In order to remain backward compatible with a common usage in Numeric. or the newaxis object. 1) >>> x[1:2] array([[[4]. . if i is not given it defaults to 0 for k > 0 and n for k < 0 . but no integer arrays or other embedded sequences.1 integers. 3. 3. 7.. The simplest case of indexing with N integers returns an array scalar representing the corresponding item. j is the stopping index.[6]]]) >>> x..[5]. 8. 5. 9]) • If the number of objects in the selection tuple is less than N . Example >>> x[5:] array([5. 9]) >>> x[1:7:2] array([1.[2].1) k where m = q + (r 6= 0) and q and r are the quotient and remainder obtained by dividing j .4. 6.i by k: j .8.e. 8. Indexing 103 . 1. Example >>> x[-2:10] array([8. 2. 4.. This selects the m elements (in the corresponding dimension) with index values i.shape (2. If j is not given it defaults to n for k > 0 and -1 for k < 0 . 1. all indices are zero-based: for the i-th index ni . Some useful concepts to remember include: • The basic slice syntax is i:j:k where i is the starting index. basic slicing is also initiated if the selection object is any sequence (such as a list) containing slice objects. Release 1. it means ni + i).

obj. any others are interpreted as :.None. If N = 1 then the returned object is an array scalar. 104 Chapter 1. . x[obj] . Release 1.. None can also be used instead of newaxis.ind2.::-1] can also be implemented as obj = (slice(1.. but (unlike lists) you can never grow the array. i.ind2. The added dimension is the position of the newaxis object in the selection tuple. Example >>> x[:.8. 6]]) • Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.5).4. Array objects . acts like repeated application of slicing using a single non-: entry. [6]]]) • Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x. • If the selection tuple has all entries : except the p-th entry which is a slice object i:j:k.:] acts like x[ind1][.. returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. where the non-: entries are successively taken (with all other non-: entries replaced by :). These objects are explained in Scalars. Note: Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. 3]. There are two types of advanced indexing: integer and Boolean. • Basic slicing with more than one non-: entry in the slicing tuple. 5.. numpy..:] under basic slicing.:].. a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding sub-array with dimension N .1. 1.shape (2.-1)).. an ndarray (of data type integer or bool).1) k < j. Slice objects can be used in the construction in place of the [start:stop:step] notation. Example >>> x[.ndim. slice(None. Only the first ellipsis is expanded.newaxis The newaxis object can be used in all slicing operations as discussed above. Thus.NumPy Reference. For example. • You may use slicing to set values in the array.newaxis. 1. Warning: The above is not true for advanced slicing.np. [4.10. i+k. or a tuple with at least one sequence object or ndarray (of data type integer or bool). In particular.. then the returned array has dimension N formed by concatenating the sub-arrays returned by integer indexing of elements i.0] array([[1.:. The size of the value to be set in x[obj] = value must be (broadcastable) to the same shape as x[obj].1 [5]. i + (m . This can be useful for constructing generic code that works on arrays of arbitrary dimension...2 Advanced indexing Advanced indexing is triggered when the selection object. 2.. 1) • An integer. x[1:10:5. x[ind1... is a non-tuple sequence object. 3.

.4)-shaped broadcasted indexing subspace.1 slice objects) it does exactly what you would expect (concatenation of repeated application of basic slicing)..1 Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view)... . and let Ns = N − Nt be the number of slice objects.k] = x[ind_1[i. . it will be referred to as if it had been promoted to a 1-tuple. it can be easier to grasp what happens. ind_N[i_1. which will be called the selection tuple..4)-shaped subspace then 1...e. or the Ellipsis object.k]. j.k]] • If Ns > 0...)-shaped subspace has been replaced with a (2. then the broadcasted indexing space is first. • The first Ellipsis object will be expanded. . ind_2[i.. and each i. i_M) over the range of the result shape and for each value of the index tuple (ind_1. .NumPy Reference. i_M] == x[ind_1[i_1.4)-shaped indexing intp array. If the indexing subspaces are separated (by slice objects).ind.3. but if you think in terms of the shapes of the arrays involved.. • If the selection tuple is smaller than N.4.30) and ind is a (2.. then as many : objects as needed are added to the end of the selection tuple so that the modified selection tuple has length N. • If Ns = 0 then the M-dimensional result is constructed by varying the index tuple (i_1. If the index subspaces are right next to each other.20. Note that Nt > 0 (or we wouldn’t be doing advanced integer indexing). This can be somewhat mind-boggling to understand. • All sequences and scalars in the selection tuple are converted to intp indexing arrays.. i_M].j. .30) because the (20.. i_M]. The expanded Ellipsis object is replaced with as many full slice (:) objects as needed to make the length of the selection tuple N . Indexing 105 . Then the result is found by letting i. then result = x[. followed by the sliced subspace of x. ..2. For the discussion below. then the broadcasted indexing space directly replaces all of the indexed subspaces in x. one indexing array and N .:] has shape (10. • After expanding any ellipses and filling out any missing : objects in the selection tuple... If we let i. k loop over the (2. ind_M): result[i_1. ..3. and any other Ellipsis objects will be treated as full slice (:) objects.4.. i_M]] Example Suppose the shape of the broadcasted indexing arrays is 3-dimensional and N is 2. Example Suppose x.3.8. This kind of selection occurs when advanced indexing is triggered and the selection object is not an array of data type bool. The rules of advanced integer-style indexing are: • If the length of the selection tuple is larger than N an error is raised.. j.. • All the integer indexing arrays must be broadcastable to the same shape. In simple cases (i.3. 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. Integer Integer indexing allows selection of arbitrary items in the array based on their N-dimensional index. then partial indexing is done.j. when the selection object is not a tuple. k run over the shape found by broadcasting ind_1 and ind_2. j... slice objects. then let Nt be the number of indexing arrays. • The shape of the output (or the needed shape of the object to be used for setting) is the broadcasted shape. ind_2[i_1. • All selection tuple objects must be convertible to intp arrays. k yields: result[i. Release 1..j.shape is (10.

3)].. as described above.j. they will always be interpreted as nonzero(obj) and the equivalent integer indexing will be done. In this case x[obj] returns a 1-dimensional array filled with the elements of x corresponding to the True values of obj.3. Release 1. Currently this returns a new array containing a copy of the values in the fields specified in the list.3 Record Access See Also: Data type objects (dtype). However..40.2.] is fundamentally different than x[(1.ind[i. The search order will be C-style (last index varies the fastest).NumPy Reference.nonzero() returns a tuple (of length obj.ndim) of integer index arrays showing the True elements of obj.30.2. its data type is a record data type.e.’field-name2’]]. which is of the same shape as x (except when the field is a sub-array) but of data type x. It is always possible to use . use x[[’field-name1’.2.3).take(ind. It is always equivalent to (but faster than) x[obj.50) because the (20.transpose() to move the subspace anywhere desired.k. You can also use Boolean arrays as element of the selection tuple.1 result[.2. then an index error will be raised. thus it is tackedon to the beginning. obj. e. As of NumPy 1.e.4. This will work with both past and future versions of NumPy. Warning: The definition of advanced indexing means that x[(1. (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 comparison operators). Indexing x[’field-name’] returns a new view to the array. The latter is equivalent to x[1. The special case when obj. axis=-2). dictionary-like.ind_1. If obj has True values at entries that are outside of the bounds of x.50) because there is no unambiguous place to drop in the indexing subspace.3]] will trigger advanced indexing.ndim is worth mentioning. Array objects .:]. then we suggest copying the returned array explicitly.ind_2] has shape (2. x. Be sure to understand why this is occurs.i.. but a FutureWarning will be issued when writing to the copy. 106 Chapter 1. the dimensions of the sub-array are appended to the shape of the result.ind_2] has shape (10. i.:.:] = x[. Also recognize that x[[1.j.20.dtype[’field-name’] and contains only the part of the data in the specified field.30.k]. i.30)-shaped subspace from X has been replaced with the (2.8. whereas x[[1. If the accessed field is a sub-array.shape be (10.2. Also record array scalars can be “indexed” this way.copy(). Then x[:.3.slice(None)]] will trigger basic slicing.3.g. x[[’field-name1’... A copy will continue to be returned for now.4). If you depend on the current behavior. returning a copy is being deprecated in favor of returning a view.3] which will trigger basic selection while the former will trigger advanced indexing. This example produces the same result as Example Now let x.10.ind_1. x[:.4. 1.4.2.40. Scalars If the ndarray object is a record array.nonzero()] where.’field-name2’]].7. Indexing into a record array can also be done with a list of field names.3..50) and suppose ind_1 and ind_2 are broadcastable to the shape (2. In such instances.4) subspace from the indices.ndim == x. the fields of the array can be accessed by indexing the array with strings.

introduced in NumPy 1.reshape(2.dtype dtype(’int32’) >>> x[’b’].float64. provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion. This page introduces some basic ways to use the object for computations on arrays in Python.reshape(2. 2) >>> x[’a’].NumPy Reference.2).zeros((2. Each element is provided one by one using the standard Python iterator interface. 4 5 An important thing to be aware of for this iteration is that the order is chosen to match the memory layout of the array instead of using a standard C or Fortran ordering.arange(6). compared to taking a copy of that transpose in C order.arange(6). Example >>> a = np. Iterating Over Arrays 107 . .shape (2. Since the Python exposure of nditer is a relatively straightforward mapping of the C array iterator API.flat returns an iterator that will iterate over the entire array (in C-contiguous style with the last index varying the fastest).shape (2. (3.dtype dtype(’float64’) 1.6. We can see this by iterating over the transpose of our previous array..1 Example >>> x = np. Release 1.int32).3) x in np.5.4 Flat Iterator indexing x.3) >>> for x in np. 2..nditer(a): print x.T): 1. 3. np. dtype=[(’a’. 1. This should be clear from the fact that x.5 Iterating Over Arrays The iterator object nditer. (’b’. 1.1 Single Array Iteration The most basic task that can be done with the nditer is to visit every element of an array.. This iterator object can also be indexed using basic slicing or advanced indexing as long as the selection object is not a tuple.8. 3) >>> x[’b’]. The shape of any returned array is therefore the shape of the integer indexing object. This is done for access efficiency.3))]) >>> x[’a’]. these ideas will also provide help working with array iteration from C or C++. Example >>> a = >>> for . reflecting the idea that by default one simply wants to visit each element without concern for a particular ordering.nditer(a. It can be used for integer indexing with 1-dimensional C-style-flat indices.. np. then concludes with how one can accelerate the inner loop in Cython.flat is a 1-dimensional view. 0 1 2 3 np.4.5.

order=’F’): print x.. print x. . 0 1 2 3 4 5 >>> for x in np.nditer(a. This can be overridden with order=’C’ for C order and order=’F’ for Fortran order. 0 3 a = np. namely the order they are stored in memory. .arange(6). Regular assignment in Python simply changes a reference in the local or global variable dictionary instead of modifying an existing variable in place... Release 1. 5]]) >>> for x in np. This means that simply assigning to x will not place the value into the element of the array. having the behavior described above. To modify the array elements...copy(order=’C’)): .nditer(a. print x. you must specify either read-write or write-only mode. Controlling Iteration Order There are times when it is important to visit the elements of an array in a specific order. irrespective of the layout of the elements in memory. the nditer treats the input array as a read-only object.. To actually modify the element of the array.nditer(a.NumPy Reference..T. 1 4 2 5 Modifying Array Values By default. 1 4 2 5 for x in np... 0 3 >>> . [3....reshape(2....reshape(2. This is controlled with per-operand flags. 2]. .copy(order=’C’) get visited in a different order because they have been put into a different memory layout.T get traversed in the same order.1 .T.3) for x in np. but rather switch x from being an array element reference to being a reference to the value you assigned.. 0 3 1 4 2 5 The elements of both a and a. x should be indexed with the ellipsis. whereas the elements of a. The nditer object provides an order parameter to control this aspect of iteration.8. x[. op_flags=[’readwrite’]): .. order=’C’): print x.nditer(a..T...] = 2 * x . Array objects .3) >>> a array([[0. The default. Example >>> >>> . is order=’K’ to keep the existing order. 4. 1.arange(6).. .. >>> a 108 Chapter 1. Example >>> a = np.

This way.. it.index). Release 1.reshape(2. you may want to visit the elements of an array in memory order. [0 1 2 3 4 5] >>> for x in np.arange(6).. the elements of a are provided by the iterator one at a time. By forcing ‘C’ and ‘F’ order.NumPy Reference.5.arange(6).nditer(a. the iterator is able to provide a single one-dimensional chunk. NumPy’s vectorized operations can be used on larger chunks of the elements being visited. This mode is enabled by specifying an iterator flag. Observe that with the default of keeping native memory order..nditer(a. . order=’F’): . . 10]]) Using an External Loop In all the examples so far. print x. it.. With this looping construct.. it is not very efficient. [ 6. This syntax explicitly works with the iterator object itself. or multidimensional index to look up values in a different array. you may want to use the index of the current element in a computation. . but use a C-order. flags=[’external_loop’]...3) >>> for x in np.finished: . The Python iterator protocol doesn’t have a natural way to query these additional values from the iterator... it has to provide three chunks of two elements each. The nditer will try to provide chunks that are as large as possible to the inner loop. whereas when forcing Fortran order.8.1 array([[ 0. We have modified the output in the examples using this looping construct in order to be more readable. and the index being tracked is the property index or multi_index depending on what was requested. A better approach is to move the one-dimensional innermost loop into your code. print x. external to the iterator. we get different external loop sizes. Example >>> a = np. 4]. The Python interactive interpreter unfortunately prints out the values of expressions inside the while loop during each iteration of the loop.3) >>> it = np. While this is simple and convenient. [0 3] [1 4] [2 5] Tracking an Index or Multi-Index During iteration. 8..nditer(a. so its properties are readily accessible during iteration. flags=[’external_loop’]): . 2. For example.. Fortran-order. Example >>> a = np..iternext() 1. print "%d <%d>" % (it[0]. Iterating Over Arrays 109 .reshape(2. so we introduce an alternate syntax for iterating with an nditer. flags=[’f_index’]) >>> while not it. the current value is accessible by indexing into the iterator. because all the looping logic is internal to the iterator.

significantly reducing the overhead of the Python interpreter.’buffered’].nditer(a..nditer(a.. [-1. When writing C code.. op_flags=[’writeonly’]) >>> while not it. In the example forcing Fortran iteration order. the chunks provided by the iterator to the inner loop can be made larger. it[0] = it.. this is generally fine... flags=[’external_loop’].arange(6).it.multi_index[0] . print x... in <module> ValueError: Iterator flag EXTERNAL_LOOP cannot be used if an index or multi-index is being tracked Buffering the Array Elements When forcing an iteration order. flags=[’external_loop’. line 1. 0 <(0. 1)> 5 <(1. . [0 3] [1 4] [2 5] >>> for x in np. flags=[’c_index’. 0)> 4 <(1.nditer(a. 0 <0> 1 <2> 2 <4> 3 <1> 4 <3> 5 <5> >>> it = np... 2)> 3 <(1.. .iternext() . order=’F’): .multi_index[1] . the inner loop gets to see all the elements in one go when buffering is enabled. flags=[’multi_index’]) >>> while not it.multi_index). however in pure Python code this can cause a significant reduction in performance.reshape(2.. print x.8. By enabling buffering mode. print "%d <%s>" % (it[0]. it.finished: .iternext() . ’external_loop’]) Traceback (most recent call last): File "<stdin>".. If you try to combine these flags. 0)> 1 <(0. 2]. flags=[’multi_index’].finished: .. [0 3 1 4 2 5] 110 Chapter 1.. Array objects . it.3) >>> for x in np.nditer(a.. 1)> 2 <(0...zeros((2. order=’F’): .1 . 2)> >>> it = np.. Example >>> a = np. the nditer object will raise an exception Example >>> a = np. it. 0. 1]]) Tracking an index or multi-index is incompatible with using an external loop...3)) >>> it = np. 1. . >>> a array([[ 0. we observed that the external loop option may provide the elements in smaller chunks because the elements can’t be visited in the appropriate order with a constant stride..NumPy Reference. Release 1. because it requires a different index value per element.nditer(a.

but neither copying nor buffering was enab In copying mode. op_dtypes=[’complex128’]): . buffering is recommended over temporary copying.. This means. that it will raise an exception if you try to treat a 64-bit float array as a 32-bit float array. In our examples.. Buffering mode mitigates the memory usage issue and is more cache-friendly than making temporary copies.’copy’]... 1. the iterator will raise an exception if the data type doesn’t match precisely. it’s generally better to let the iterator handle the copying or buffering instead of casting the data type yourself in the inner loop. print np.reshape(2. it enforces ‘safe’ casting.8. the rule ‘same_kind’ is the most reasonable rule to use. With temporary copies. op_flags=[’readonly’. Release 1. then iteration is done in the copy.nditer(a..nditer(a.NumPy Reference. one may want to do all computations on 64-bit floats. Iterating Over Arrays 111 . Except when writing low-level C code. Without enabling copies or buffering mode. buffering is used by the ufuncs and other functions to support flexible inputs with minimal memory overhead.nditer(a.5. Buffering mode is specified as an iterator flag. where the whole array is needed at once outside the iterator. . since it will allow conversion from 64 to 32-bit float.. By default..3) . Within NumPy.sqrt(x). The major drawback of temporary copies is that the temporary copy may consume a large amount of memory. Example >>> a = np. For instance. ‘copy’ is specified as a per-operand flag.1 Iterating as a Specific Data Type There are times when it is necessary to treat an array as a different data type than it is stored as.3 >>> for x in np. temporary copies and buffering mode.73205080757j 1.. particularly if the iteration data type has a larger itemsize than the original one.73205080757j 1.reshape(2. This is done to provide control in a per-operand fashion.sqrt(x). a copy of the entire array is made with the new data type... .41421356237+0j) >>> for x in np.3 >>> for x in np. Example >>> a = np.3) . . line 1.. Except for special cases. Traceback (most recent call last): File "<stdin>". . print np. op_dtypes=[’complex128’]): .arange(6).41421356237+0j) The iterator uses NumPy’s casting rules to determine whether a specific conversion is permitted.sqrt(x). we will treat the input array with a complex data type. in <module> TypeError: Iterator operand required copying or buffering. Write access is permitted through a mode which updates the original array after all the iteration is complete. even if the arrays being manipulated are 32-bit floats.arange(6). Example 1. flags=[’buffered’]. for example. There are two mechanisms which allow this to be done. so that we can take square roots of negative numbers. print np.. op_dtypes=[’complex128’]): ..41421356237j 1j 0j (1+0j) (1. but not from float to int or from complex to float. In many cases. 1..41421356237j 1j 0j (1+0j) (1.

] = x / 2.nditer(a... .nditer(a.1 >>> a = np. Traceback (most recent call last): File "<stdin>". 0:0 112 a = np.b]): print "%d:%d" % (x. print x. in <module> TypeError: Iterator operand 0 dtype could not be cast from dtype(’float64’) to dtype(’int32’) accordi One thing to watch out for is conversions back to the original data type when using a read-write or write-only operand.. op_dtypes=[’int32’]. casting=’same_kind’): . A common case is to implement the inner loop in terms of 64-bit floats..arange(3) b = np.0 2. . we print out the result of broadcasting a one and a two dimensional array together.. in <module> TypeError: Iterator requested dtype could not be cast from dtype(’float64’) to dtype(’int64’).. op_flags=[’readwrite’]. 1:1 2:2 0:3 1:4 2:5 Chapter 1. op_dtypes=[’float64’]. The nditer object can apply these rules for you when you need to write such a function.reshape(2. While in read-only mode....nditer([a. line 1. Traceback (most recent call last): File "<stdin>". Traceback (most recent call last): File "<stdin>".... casting=’same_kind’): .arange(6. y in np.. flags=[’buffered’].arange(6) >>> for x in np... op_dtypes=[’float32’]): . . in <module> TypeError: Iterator operand 0 dtype could not be cast from dtype(’float64’) to dtype(’float32’) accor >>> for x in np. flags=[’buffered’]. Example >>> >>> >>> .) >>> for x in np. Array objects .. x[. flags=[’buffered’].. the op 1.0 4.y). an integer array could be provided. op_dtypes=[’float32’]. This is called broadcasting..2 Broadcasting Array Iteration NumPy has a set of rules for dealing with arrays that have differing shapes which are applied whenever functions take multiple operands which combine element-wise. line 1.. 0.. As an example.0 1.arange(6). read-write mode will raise an exception because conversion back to the array would violate the casting rule.0 ..0 3. print x.8. Example >>> a = np. and use ‘same_kind’ casting to allow the other floating-point types to be processed as well. print x.NumPy Reference. flags=[’buffered’]. Release 1. casting=’same_kind’): .nditer(a.3) for x..5.0 >>> for x in np.. . ..0 5.. line 2..nditer(a. .

. 9]) By default. Let’s start with a minimal function definition excluding ‘out’ parameter support.3) Iterator-Allocated Output Arrays A common case in NumPy functions is to have outputs allocated based on the broadcasting of the input. If the default were ‘readwrite’. and it handled the rest. >>> square([1. While we’re at it. as these are what you will typically want for performance reasons. we have to explicitly provide those flags. . in <module> ValueError: operands could not be broadcast together with shapes (2) (2.NumPy Reference.. return it. Release 1. When adding the ‘out’ parameter.3]) array([1.nditer([a. it = np. To see how to generalize the square function to a reduction.5. 4.nditer([a.. print "%d:%d" % (x.. Example 1. Example >>> def square(a): . the nditer uses the flags ‘allocate’ and ‘writeonly’ for operands that are passed in as None.. and additionally have an optional parameter called ‘out’ where the result will be placed when it is provided. The reason ‘readonly’ is the default for input arrays is to prevent confusion about unintentionally triggering a reduction operation.. Traceback (most recent call last): File "<stdin>"... let’s also introduce the ‘no_broadcast’ flag..8. Iterating Over Arrays 113 . y in np.] = x*x . None]) . a topic which is covered later in this document. because we only want one input value for each output. This means we were able to provide just the two operands to the iterator. We’ll show how this works by creating a function square which squares its input.2. y in it: .y). It would already raise an error because reductions must be explicitly enabled in an iterator flag. the iterator raises an exception which includes the input shapes to help diagnose the problem. This is important. which will prevent the output from being broadcast...b]): . look at the sum of squares function in the section about Cython. Aggregating more than one input value is a reduction operation which requires special handling. The nditer object provides a convenient idiom that makes it very easy to support this mechanism. because if someone passes in an array as ‘out’.arange(2) >>> b = np... For completeness. Example >>> a = np. and our inner loop would fail. the iterator will default to ‘readonly’. but the error message that results from disabling broadcasting is much more understandable for end-users..3) >>> for x.. y[. any broadcasting operation would also trigger a reduction.reshape(2. for x.. line 1.arange(6). we’ll also add the ‘external_loop’ and ‘buffered’ flags.1 When a broadcasting error occurs.operands[1] .

3]) array([1. op_axes=[[0. out]. Array objects . 9. The iterator will have three dimensions. It is also possible to do this with newaxis indexing.NumPy Reference.2. 0]. 1]. 9]) >>> b = np. line 4.3).. ’allocate’. y[. with a final result of [0. None]) >>> for x.. 4. line 1. z[. 0..nditer([a. return it.. it = np. out=b) Traceback (most recent call last): File "<stdin>"...arange(8). so we can provide None instead of constructing another list.. y.. 0..arange(6). -1]. Example >>> a = np. . None]..]) >>> b array([ 1. -1. We’ll do a simple outer product.. The second list picks out the two axes of the second operand. 0. b. out=None): . but we will show you how to directly use the nditer op_axes parameter to accomplish this with no intermediate views. Release 1.nditer([a. Everything to do with the outer product is handled by the iterator setup..)) >>> square([1.. but shouldn’t overlap with the axes picked out in the first operand. z in it: .. 0. The op_axes parameter needs one list of axes for each operand... so op_axes will have two 3-element lists... flags=[’external_loop’].3) Outer Product Iteration Any binary operation can be extended to an array operation in an outer product fashion like in outer. y in it: . in <module> File "<stdin>". -1.reshape(2. and the nditer object provides a way to accomplish this by explicitly mapping the axes of the operands. 4... Suppose the first operand is one dimensional and the second operand is two dimensional.1 >>> def square(a. >>> it.]) >>> square(np. . for x. ’no_broadcast’]]) . ’buffered’]. placing the dimensions of the first operand before the dimensions of the second operand.operands[1] . The output operand maps onto the iterator axes in the standard manner.8....zeros((3. .. in square ValueError: non-broadcastable output operand with shape (3) doesn’t match the broadcast shape (2. out=b) array([ 1. >>> square([1.2. 114 Chapter 1. and provides a mapping from the iterator’s axes to the axes of the operand.. -1]..3]..] = x*x . 4.. [-1. 1].4) >>> it = np. flags = [’external_loop’. The first list picks out the one axis of the first operand.operands[2] array([[[ 0.reshape(2. The operation in the inner loop is a straightforward multiplication. Its list is [-1.. .arange(3) >>> b = np. op_flags = [[’readonly’]. and is -1 for the rest of the iterator axes. [’writeonly’..] = x*y . 9.

4) >>> b = np.nditer([a. op_axes=[None.. For a simple example.. 70. 14]]]) Reduction Iteration Whenever a writeable operand has fewer elements than the full iteration space..sum(a) 276 Things are a little bit more tricky when combining reduction and allocated operands. 0.3. [54. 38].NumPy Reference. . 0.1 [ [[ [ [[ [ 0. >>> it. op_flags=[[’readonly’]. None].] += x .. Normally the iterator construction involves copying the first buffer of data from the readable arrays into the buffer. and garbage results will be produced. 10.8. flags=[’reduce_ok’.] += x .] = 0 >>> for x. 6]. 22. initialization of the operand after this buffering operation is complete will not be reflected in the buffer that the iteration starts with.operands[1] array([[ 6.reshape(2. . Before iteration is started. ’external_loop’]. The nditer object requires that any reduction operand be flagged as read-write.. b]. and only allows reductions when ‘reduce_ok’ is provided as an iterator flag. . 86]]) >>> np.arange(24)... 0]]. 5. flags=[’reduce_ok’. y[. 22. that operand is undergoing a reduction. [54.5. so it may be read into a buffer. Unfortunately.-1]]) >>> it.. 2.operands[1][. 86]]) To do buffered reduction requires yet another adjustment during the setup. y[. Example >>> a = np.. Any reduction operand is readable.. taking sums along the last axis of a.sum(a. 7]].array(0) >>> for x.. 4.. [’readwrite’.. 3]. Release 1.. 38].. Example >>> a = np. 0.nditer([a. Here’s how we can do this. 70.. 8. any reduction operand must be initialized to its starting values. axis=2) array([[ 6.. [0...arange(24). y in np. 4. [’readwrite’]]): . consider taking the sum of all elements in an array..reshape(2. >>> b array(276) >>> np. ’external_loop’].4) >>> it = np. 1.3. 2. 12. op_flags=[[’readonly’]. Iterating Over Arrays 115 .1. 1. ’allocate’]]. 0. 6. y in it: .

. To start.. we’ll create a sum of squares function..operands[1][. ’external_loop’. op_axes=[None. Here’s how the previous example looks if we also enable buffering.. y in it: ..nditer([arr. axeslist[i] = ax . ’delay_bufalloc’]..operands[1] array([[ 6.. while giving the inner loop to Cython. axis=None.. Cython is a good middle ground with reasonable performance tradeoffs. .. . ...1 The iterator flag “delay_bufalloc” is there to allow iterator-allocated reduction operands to exist together with buffering. if axis is None: . y[. the iterator will leave its buffers uninitialized until it receives a reset.3. axeslist = [1] * ndim . axis = (axis..-1]]) >>> it..NumPy Reference. axeslist[i] = -1 . arr. When this flag is set.. Example >>> def axis_to_axeslist(axis... out]..... op_axes=[None.... return [-1] * ndim . 38].. Here’s how this looks. 22.5... if axeslist[i] != -1: .. 116 Chapter 1. Array objects . For the nditer object. axeslist = axis_to_axeslist(axis. for i in axis: . None].8. let’s implement this function in straightforward Python.reset() >>> for x.. it = np. Example >>> a = np. so we will need to construct a list for the op_axes parameter... >>> def sum_squares_py(arr. else: . 86]]) 1. For our example.. op_flags=[[’readonly’]. flags=[’reduce_ok’.. and buffering. [0.arange(24).1. ax = 0 . but for those who are not comfortable with C or C++.. ’buffered’. ’allocate’]].] = 0 >>> it.. after which it will be ready for regular iteration.ndim) .3 Putting the Inner Loop in Cython Those who want really good performance out of their low level operations should strongly consider directly using the iteration API provided in C. [54. this means letting the iterator take care of broadcasting. ’allocate’]]. return axeslist . dtype conversion.) ..4) >>> it = np. axeslist].. . Release 1. ’external_loop’...... ’delay_bufalloc’]. 70. . ndim): . op_flags=[[’readonly’].. [’readwrite’. ’buffered’.] += x ..nditer([a.. ...reshape(2.... flags=[’reduce_ok’.. We want to support an ‘axis’ parameter similar to the numpy sum function. >>> it.. out=None): . ax += 1 .. for i in range(ndim): .. [’readwrite’.. if type(axis) is not tuple: .

. ’external_loop’.] += x*x) with Cython code that’s specialized for the float64 dtype.8..] = 0 . the arrays provided to the inner loop will always be one-dimensional... [’readwrite’.reset() for xarr. it..pyx: import numpy as np cimport numpy as np cimport cython def axis_to_axeslist(axis.. ’float64’]) .nditer([arr.arange(6).ndim) it = np.. op_dtypes=[’float64’. 50. out]....3) >>> sum_squares_py(a) array(55.]) To Cython-ize this function.reshape(2.NumPy Reference. op_dtypes=[’float64’. flags=[’reduce_ok’... for x.ndarray[double] x cdef np.operands[1][. out=None): cdef np..boundscheck(False) def sum_squares_cy(arr. axis=-1) array([ 5.5.. ’float64’]) it. ’buffered’... op_flags=[[’readonly’]. axeslist]. Iterating Over Arrays 117 . ’delay_bufalloc’].reset() . >>> a = np. return it.shape[0] 1. we replace the inner loop (y[. With the ‘external_loop’ flag enabled. Release 1.1 . arr.operands[1][. axis=None.) axeslist = [1] * ndim for i in axis: axeslist[i] = -1 ax = 0 for i in range(ndim): if axeslist[i] != -1: axeslist[i] = ax ax += 1 return axeslist @cython. y in it: ..] += x*x .. op_axes=[None. so very little checking needs to be done.ndarray[double] y cdef int size cdef double value axeslist = axis_to_axeslist(axis. ’allocate’]]... y[. ndim): if axis is None: return [-1] * ndim else: if type(axis) is not tuple: axis = (axis. Here’s the listing of sum_squares.. yarr in it: x = xarr y = yarr size = x.operands[1] . it.] = 0 it..0) >>> sum_squares_py(a..

but you may have to find some Cython tutorials to tell you the specifics for your system configuration. Therefore. Therefore.8. and can be simply a matter of choice.reshape(2.all(sum_squares_py(a.7 -fno-strict-aliasing -o sum_s Running this from the Python interpreter produces the same answers as our native Python/NumPy code did. 50. 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. axis=-1)) True >>> np.NumPy Reference.sum(a*a.6 Standard array subclasses The ndarray in NumPy is a “new-style” Python built-in-type. best of 3: 37. Array objects .operands[1] On this machine. and so the choice may not be significant in the end. best of 3: 11. it can be inherited from (in Python or in C) if desired. axis=-1)) True 1.arange(6).1000) >>> timeit sum_squares_py(a. If you are confident that your use of the array object can handle any subclass of an ndarray. axis=-1) == np.sum(a*a. Note that asarray always returns the base-class ndarray.pyx $ gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -I/usr/include/python2. then asanyarray can be used to allow subclasses to propagate more cleanly through your subroutine. axis=-1) 100 loops.9 ms per loop >>> timeit sum_squares_cy(a. axis=-1) 10 loops. under strict 118 Chapter 1.8 ms per loop >>> np.0) >>> sum_squares_cy(a.: $ cython sum_squares.1 for i in range(size): value = x[i] y[i] = y[i] + value * value return it. it can form a foundation for many useful classes. axis=-1) == np. axis=-1) array([ 5.sum(a*a.random.3) >>> sum_squares_cy(a) array(55. building the .. 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.pyx file into a module looked like the following. axis=-1) 10 loops. Release 1.]) Doing a little timing in IPython shows that the reduced overhead and memory allocation of the Cython inner loop is providing a very nice speedup over both the straightforward Python code and an expression using NumPy’s built-in sum function. In principal a subclass could redefine any aspect of the array and therefore. best of 3: 20. NumPy has several tools for simplifying how your new object interacts with other array objects.1 ms per loop >>> timeit np.: >>> a = np.rand(1000.all(sum_squares_cy(a. Example >>> from sum_squares import sum_squares_cy >>> a = np.

1. results will be written to the object returned by __array__. where obj is a subclass (subtype) of the ndarray. or the output object if one was specified. 2.2 Matrix objects matrix objects inherit from the ndarray and therefore.__array_finalize__(self ) This method is called whenever the system internally allocates a new array from obj.__array_prepare__(array. however. this method is called on the input object with the highest array priority. context=None) At the end of every ufunc. most subclasses of the arrayobject will not redefine certain aspects of the array object such as the buffer interface. There are six important differences of matrix objects. numpy. 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. The output array is passed in and whatever is returned is passed to the ufunc. rather than element-by-element multiplication. they have the same attributes and methods of ndarrays.NumPy Reference. Subclasses inherit a default implementation of this method. Standard array subclasses 119 . Release 1.ravel() is still twodimensional (with a 1 in the first dimension) and item selection returns two-dimensional objects so that sequence behavior is fundamentally different than arrays.__array_wrap__(array. Subclasses inherit a default value of 1. This has far-reaching implications.0 for this attribute. which transforms the array into a new instance of the object’s class. that may lead to unexpected results when you use matrices but expect them to act like arrays: 1. numpy. One important example. 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. Matrix objects can be created using a string notation to allow Matlab-style syntax where spaces separate columns and semicolons (‘. context=None) At the beginning of every ufunc. however.6. asanyarray would rarely be useful.1 Special attributes and methods See Also: Subclassing ndarray Numpy provides several hooks that subclasses of ndarray can customize: numpy.” Subclasses inherit a default implementation of this method that does nothing. 1. in that m. or to update meta-information from the “parent. Subclasses inherit a default implementation of this method which simply returns the output array unmodified. numpy. or the output object if one was specified.’) separate rows. or the attributes of the array.1 guidelines.__array__([dtype ]) If a class having the __array__ method is used as the output object of an ufunc.6.6. 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. It can be used to change attributes of self after construction (so as to ensure a 2-d matrix for example). However. The ufunc-computed array is passed in and whatever is returned is passed to the user. numpy.8. 1. this method is called on the input object with the highest array priority. Matrix objects are always two-dimensional.

Matrix objects over-ride power to be matrix raised to a power. and power. 5.) to get an array object holds for this fact. Array objects .H hermitian (conjugate) transpose matrix. Release 1. such as * (matrix multiplication) and ** (matrix power). 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. matrix asmatrix(data[. Matrices have special attributes which make calculations easier.NumPy Reference. ‘*’. Make sure you understand this for functions that you may want to receive matrices.matrix Returns a matrix from an array-like object.T matrix. or from a string of data. or from a string of data. These are matrix..I matrix. The name “mat “is an alias for “matrix “in NumPy. A matrix is a specialized 2-D array that retains its 2-D nature through operations. The default __array_priority__ of matrix objects is 10. ldict. strings.1 3.H matrix. it is interpreted as a matrix with commas or spaces separating columns. Interpret the input as a matrix. and anything else that can be converted to an ndarray . It has certain special operators. to be matrix-multiplication and matrix power.A transpose hermitian (conjugate) transpose inverse base array matrix. ‘**’.. dtype : data-type Data-type of the output matrix. class numpy. gdict]) Returns a matrix from an array-like object. then you must use the ufuncs multiply and power to be sure that you are performing the correct operation for all inputs.I inverse matrix. If your subroutine can accept sub-classes and you do not convert to base. nested sequence. Build a matrix object from a string. Matrix objects over-ride multiplication to be matrix-multiplication. The same warning about using power inside a function that uses asanyarray(.0. and therefore mixed operations with ndarrays always produce matrices. 4. Matrices can be created from other matrices.class arrays. or array. Parameters data : array_like or string If data is a string.T transpose matrix. respectively. 6.8. Especially in light of the fact that asanyarray(m) returns a matrix when m is a matrix. dtype]) bmat(obj[.A base array Warning: Matrix objects over-ride multiplication. copy : bool 120 Chapter 1. and semicolons separating rows.

1 If data is already an ndarray. 4]]) matrix([[1. then this flag determines whether the data is copied (the default). [3. The imaginary part of the array.6.H hermitian (conjugate) transpose matrix.A base array matrix.I inverse matrix. Standard array subclasses 121 . Information about the memory layout of the array. 2].8. [3. Python buffer object pointing to the start of the array’s data. Tuple of bytes to step in each dimension when traversing an array.NumPy Reference. Length of one array element in bytes. matrix. See Also: array Examples >>> >>> [[1 [3 a = np. A 1-D iterator over the array. The real part of the array. Data-type of the array’s elements. An object to simplify the interaction of the array with the ctypes module. or whether a view is constructed.A1 1-d base array matrix. 1. Release 1.matrix(’1 2. 2].matrix([[1. Tuple of array dimensions.base Base object if memory is from some other object. Total bytes consumed by the elements of the array.T transpose matrix. 4]]) Attributes A A1 H I T base ctypes data dtype flags flat imag itemsize nbytes ndim real shape size strides base array 1-d base array hermitian (conjugate) transpose inverse transpose Base object if memory is from some other object. 3 4’) print a 2] 4]] >>> np. Number of array dimensions. Number of elements in the array.

ndim): A ctypes array of length self. strides. shape. etc.2. Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self. as well as documented private attributes): •data: A pointer to the memory area of the array as a Python integer. whose memory is shared with x: >>> y = x[2:] >>> y. For example: •strides_as(obj): Return the strides tuple as an array of some other c-types type.shape_as(ctypes. self. For example: self.POINTER(ctypes.4]) >>> x.base is x True matrix. among others.ndim where the basetype is the C-integer corresponding to dtype(‘p’) on this platform. shape. The c_intp type is defined accordingly in numpy. User Beware! The value of this attribute is exactly the same as self. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. See Also: numpy.ndim where the basetype is the same as for the shape attribute. This strides information is important for showing how many bytes must be jumped to get to the next element in the array. calling self.c_longlong)._array_interface_[’data’][0].data_as(ctypes.8. and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library.3.array([1.c_void_p).ctypes An object to simplify the interaction of the array with the ctypes module. Parameters None Returns c : Python object Possessing attributes data. or not in correct byte-order. The returned object has. Release 1. The ctypes array contains the shape of the underlying array.ctypeslib.strides_as(ctypes. For example.ctypeslib Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes. This memory area may contain data that is not aligned. •shape_as(obj): Return the shape tuple as an array of some other c-types type. •data_as(obj): Return the data pointer cast to a particular c-types object. c_long.base is None True Slicing creates a view.ndim): A ctypes array of length self.NumPy Reference. •shape (c_intp*self. data. 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. 122 Chapter 1.c_short). or c_longlong depending on the platform. The memory area may not even be writeable._as_parameter_ is equivalent to self.1 Examples The base of an array that owns its memory is None: >>> x = np.data_as(ctypes. This base-type could be c_int. •strides (c_intp*self.c_double)). This ctypes array contains the strides information from the underlying array. Array objects .

strides <numpy. Standard array subclasses 123 ._internal.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.data_as(ctypes.ctypes. In the latter case._internal. You can avoid this problem using either c=a+b or ct=(a+b).c_long)). 3]]) >>> x. Examples >>> import ctypes >>> x array([[0.dtype’> matrix._internal.ctypes.core.dtype dtype(’int32’) >>> type(x.data_as(ctypes.contents c_longlong(4294967296L) >>> x.c_longlong)).POINTER(ctypes.6.ctypes.data_as(ctypes. [2.flags Information about the memory layout of the array.core._internal.c_long_Array_2 object at 0x01FCE620> >>> x.POINTER(ctypes.dtype Examples >>> x array([[0. 1.especially on temporary arrays or arrays constructed on the fly. the object will still have the as parameter attribute which will return an integer equal to the data attribute.c_long_Array_2 object at 0x01FCE620> >>> x.ctypes.core.POINTER(ctypes.ctypes. In particular. For example.8. then the ctypes attribute of array objects still returns something useful.data_as(ctypes. matrix.data 30439712 >>> x. If the ctypes module is not available.c_longlong_Array_2 object at 0x01F01300> matrix. Release 1.LP_c_long object at 0x01F01300> >>> x.shape <numpy.c_long_Array_2 object at 0x01FFD580> >>> x.ctypes. 3]]) >>> x.ctypes.contents c_long(0) >>> x.strides_as(ctypes.NumPy Reference.data Python buffer object pointing to the start of the array’s data.ctypes. 1].c_long) <numpy. ct will hold a reference to the array until ct is deleted or re-assigned.dtype Data-type of the array’s elements.1 Be careful using the ctypes attribute .dtype) <type ’numpy. but ctypes objects are not returned and errors may be raised instead.ctypes.ctypes.shape_as(ctypes. calling (a+b).core. 1].c_long)) <ctypes. [2. Parameters None Returns d : numpy dtype object See Also: numpy.c_longlong) <numpy.

itemsize for Fortran-style contiguous arrays is true. This is clear for 1-dimensional arrays. Fortran-style contiguous segment. Array objects . so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.setflags. Only the UPDATEIFCOPY. When this array is deallocated. Arrays can be both C-style and Fortran-style contiguous simultaneously.strides[-1] == self. DATA (O) WRITEThe data area can be written to. locking a base object does not lock any views that already reference it. and ALIGNED flags can be changed by the user. (C) F_CONTIGUOUS The data is in a single. WRITEABLE. COPY (U) FNC F_CONTIGUOUS and not C_CONTIGUOUS. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). Attributes C_CONTIGUOUS The data is in a single. Release 1.writeable). etc.NumPy Reference. (The opposite is not true. or by calling ndarray. However.shape[dim] == 1 or the array has no elements.) inherits WRITEABLE from its base array at creation time. making it read-only. the base array DATEIFwill be updated with the contents of this array. BEHAVED ALIGNED and WRITEABLE. in that a view of a locked array may not be made writeable.flags.strides[0] == self.8. •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. or by using lowercased attribute names (as in a. ALIGNED The data and all elements are aligned appropriately for the hardware. (B) CARRAY BEHAVED and C_CONTIGUOUS. (F) OWNThe array owns the memory it uses or borrows it from another object. but a (W) view of a writeable array may be subsequently locked while the base array remains writeable. (CA) FARRAY BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS. •ALIGNED can only be set True if the data is truly aligned. It does not generally hold that self. currently. The array flags cannot be set arbitrarily: •UPDATEIFCOPY can only be set False. ABLE A view (slice.flags[’WRITEABLE’]). Short flag names are only supported in dictionary access. (A) UPThis array is a copy of some other array.strides[dim] may be arbitrary if arr. via direct assignment to the attribute or dictionary entry. (FA) 124 Chapter 1. C-style contiguous segment. Even for contiguous arrays a stride for a given dimension arr.1 Notes The flags object can be accessed dictionary-like (as in a.itemsize for C-style contiguous arrays or self. but can also be true for higher dimensional arrays. Setting this to False locks the data.) Attempting to change a non-writeable array raises a RuntimeError exception.

3]]) >>> x.NumPy Reference.flatiter’> An assignment example: >>> x.reshape(2. 3]]) matrix. x array([[3. Standard array subclasses 125 . 0.2. 3]. [2.8.imag.flat[3] 5 >>> type(x. 0+1j]) >>> x.float64) >>> x.flat A 1-D iterator over the array. 1.imag array([ 0.array([1. 4]. 3) >>> x array([[1.6.3].70710678]) >>> x. which acts similarly to. 5].1 matrix.flat) <type ’numpy. x array([[3.3]. Release 1. This is a numpy. See Also: flatten Return a copy of the array collapsed into one dimension. 5.flat = 3.dtype dtype(’float64’) matrix. 6]]) >>> x.flat[3] 4 >>> x.array([1. Examples >>> x = np. 1. but is not a subclass of.T. 6]]) >>> x. 3. dtype=np.flatiter instance.T array([[1. [3. . 3].itemsize Length of one array element in bytes. [4.arange(1. flatiter Examples >>> x = np.imag The imaginary part of the array.2. 7). Examples >>> x = np. Python’s built-in iterator object. 3]. 2. dtype=np. 3. [3.sqrt([1+0j. [3.itemsize 8 >>> x = np.flat[[1.complex128) 1.4]] = 1.

real equivalent function Examples >>> x = np.NumPy Reference.dtype dtype(’float64’) matrix. 3]) x.zeros((2.2).sqrt([1+0j.ndim y = np.array([1. 4)) y. Release 1.shape Tuple of array dimensions. 0+1j]) >>> x. 0. Notes May be used to “reshape” the array. dtype=np.zeros((3.70710678]) >>> x. Examples >>> >>> 1 >>> >>> 3 x = np.itemsize 16 matrix. Examples >>> x = np. 2. .real The real part of the array. 4]) >>> x.complex128) >>> x.shape (4. 3.ndim matrix.itemsize 480 matrix. 2. as long as this would not require a change in the total number of elements Examples >>> x = np. Array objects .zeros((2. Notes Does not include memory consumed by non-element attributes of the array object.array([1.nbytes 480 >>> np. 4)) 126 Chapter 1.ndim Number of array dimensions.real array([ 1.shape) * x. 3.real.) >>> y = np. 3.nbytes Total bytes consumed by the elements of the array.1 >>> x. See Also: numpy.8.5.prod(x.

arange(2*3*4).. but 20 bytes (5 values) to get to the same position in the next row.shape). i[n]) in an array a is: offset = sum(np.complex128) >>> x. 3].stride_tricks. 0. 7]. As such.. 0. 0. 11]].. 2). 7. 14. 13. [5. Release 1.shape = (3..e. we have to skip 4 bytes (1 value) to move to the next column. 0. 0. 15]. 6) Traceback (most recent call last): File "<stdin>". the product of the array’s dimensions. 0. 2...8. i[1]. 0. 0. 4).as_strided Notes Imagine an array of 32-bit integers (each 4 bytes): x = np.reshape(np. the strides for the array x will be (20.NumPy Reference.3. 6.. 2. [ 0. 0. 0.. Examples >>> x = np. 22. Standard array subclasses 127 .rst” file in the NumPy reference guide.4)) >>> y array([[[ 0.size Number of elements in the array. Examples >>> y = np.prod(x.shape (2. dtype=np. (2. 0. 9.1 >>> y.. . 17. 0..zeros((3.6. 8.strides Tuple of bytes to step in each dimension when traversing an array. 5. 0.shape) 30 matrix.size 30 >>> np.prod(a... dtype=np... [16. 3. 6. The byte offset of element (i[0]. 0.. 0. [ 0.array(i) * a. 19]... line 1.. 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. 4]. 0.strides) A more detailed explanation of strides can be found in the “ndarray. in <module> ValueError: total size of new array must be 0.]. For example.]]) unchanged matrix.int32) This array is stored in memory as 40 bytes.. 0. 3. i. one after the other (known as a contiguous block of memory).lib.array([[0. [ 4. 9]]. 21. See Also: numpy. >>> y. [ 8. 0. [[12.shape = (3. 0.. [20.. 8) >>> y array([[ 0. 1. 4) >>> y. 23]]]) 1.. 5. Equivalent to np.. 10.. 18. 1. 0..].

NumPy Reference. Chapter 1.1 >>> y. element-wise.0) >>> x.array((1. Return self as a flattened ndarray. out]) diagonal([offset.1. mode]) clip(a_min. Array objects .2]) >>> offset = sum(i * x. Return specified diagonals. Returns a field of the given array as a certain type. Return the cumulative product of the elements along the given axis. Return the minimum value along an axis. dtype. dtype. 4) >>> y[1.arange(5*6*7*8). out]) dump(file) dumps() fill(value) flatten([order]) getA() getA1() getH() getI() getT() getfield(dtype[. Return a copy of the array collapsed into one dimension. order]) astype(dtype[. Return selected slices of this array along given axis. cast to a specified type. kind. if possible) Return the maximum value along an axis. Return an array whose values are limited to [a_min. out]) 128 Test whether all matrix elements along a given axis evaluate to True.1))) >>> offset/y.1. Returns the indices that would sort this array. Insert scalar into an array (scalar is cast to array’s dtype. out]) argmax([axis.reshape(np. Copy an element of an array to a standard Python scalar and return it. Returns the (multiplicative) inverse of invertible self. out]) min([axis.transpose(2. out.8)). Swap the bytes of the array elements Use an index array to construct a new array from a set of choices. out]) cumsum([axis.strides) >>> x[3. dtype.5.6. Returns the (complex) conjugate transpose of self.8. Returns the transpose of the matrix.3. out]) mean([axis.2.5. Dot product of two arrays. a_max]. axis. out]) argpartition(kth[. subok. (5. Dump a pickle of the array to the specified file. offset]) item(*args) itemset(*args) max([axis. 224. copy]) byteswap(inplace) choose(choices[.7. Fill the array with a scalar value. kind. Returns the indices that would partition this array. out]) argmin([axis. 1344) >>> i = np. Complex-conjugate all elements. Test whether any array element along a given axis evaluates to True. out]) compress(condition[. axis2]) dot(b[.strides (48.strides (32. Return the cumulative sum of the elements along the given axis. Return the complex conjugate. Copy of the array. Return self as an ndarray object. Return a copy of the array.itemsize 17 >>> x = np. axis1. Returns the pickle of the array as a string. 16. a_max[.array([3.strides * np.1.itemsize 813 Methods all([axis. order]) argsort([axis.2] 813 >>> offset / x.2.1] 17 >>> offset=sum(y. 4. axis. Return the indices of the minimum values along an axis. casting. Returns the average of the matrix elements along the given axis. out]) any([axis. out]) conj() conjugate() copy([order]) cumprod([axis. order. Indices of the maximum values along an axis. Release 1.

7]. False. False. Change shape and size of array in-place. Return a view of the array with axis1 and axis2 interchanged. [ 4. Construct a Python string containing the raw data bytes in the array. Return a flattened array.matrix(np. y matrix([[0. mode]) tofile(fid[. out. Return the standard deviation of the array elements along the given axis. Return a with each element rounded to the given number of decimals. 5. dtype[. Peak-to-peak (maximum . Returns a view of the array with axes transposed. dtype. 2. Rearranges the elements in the array in such a way that value of the element in kth po Return the product of the array elements over the given axis. 3]. 3]]) >>> (x == y) matrix([[ True. ALIGNED.all(axis=None. 10. 1.flat[n] = values[n] for all n in indices. 11]]) >>> y = x[0].all‘ for complete descriptions See Also: numpy. respectively. 1. in-place. out=None) Test whether all matrix elements along a given axis evaluate to True. True. mode]) ravel([order]) repeat(repeats[. Find indices where elements of v should be inserted in a to maintain order. and UPDATEIFCOPY. 9. order]) resize(new_shape[. order]) squeeze([axis]) std([axis. Sort an array. out]) put(indices. Write array to a file as text or binary (default).40 – continued from previous page Return the array with the same data viewed with a different byte order. kind. out. Repeat elements of an array. dtype. axis1. [False. axis2. out]) searchsorted(v[.4))). Examples >>> x = np. False.all() 1. Release 1. Put a value into a specified place in a field defined by a data-type. Returns an array containing the same data with a new shape. Return an array formed from the elements of a at the given indices.1 newbyteorder([new_order]) nonzero() partition(kth[. ddof]) view([dtype.minimum) value along the given axis. side. Set array flags WRITEABLE. out. type]) Table 1. [ 8. False]].all Notes This is the same as ndarray. x matrix([[ 0. along the given axis. Return the matrix as a (possibly nested) list. Returns the variance of the matrix elements. refcheck]) round([decimals.arange(12). Remove single-dimensional entries from the shape of a. Parameters See ‘numpy. dtype. dtype.NumPy Reference. Set a. dtype. False]. axis]) reshape(shape[. 6. sep. ddof]) sum([axis. axis. but it returns a matrix object. matrix.all. out]) swapaxes(axis1. New view of array with the same data. kind. offset]) setflags([write. Return the indices of the elements that are non-zero. dtype=bool) >>> (x == y).reshape((3. Returns the sum of the matrix elements. False. along the given axis. True]. True. 2. [False. out]) ptp([axis. axis2) take(indices[.8. format]) tolist() tostring([order]) trace([offset.6. out]) transpose(*axes) var([axis. sorter]) setfield(val. axis. values[. Return the sum along diagonals of the array. align. Standard array subclasses 129 . uic]) sort([axis. order]) prod([axis.

argmax Notes This is the same as ndarray. dtype=bool) >>> (x == y). False.matrix(np. Parameters See ‘numpy. 11]]) >>> x. 6. [ 4.argmax(0) matrix([[2. [False]]. optional Output to existing array instead of creating new one. otherwise. 1. out=None) Indices of the maximum values along an axis. False]]. [False].argmin‘ for complete descriptions. 10. 5. returns ndarray matrix. 3]. 2]]) >>> x.NumPy Reference. False. x matrix([[ 0. must have same shape as expected output Returns any : bool.reshape((3.arange(12).8. 9.argmax(1) matrix([[3]. 7]. ndarray Returns a single bool if axis is None.all(1) matrix([[ True]. out=None) Return the indices of the minimum values along an axis. 2. [3]]) matrix. 130 Chapter 1.1 False >>> (x == y). out=None) Test whether any array element along a given axis evaluates to True. Refer to numpy. Array objects . dtype=bool) matrix. 2. [ 8. Release 1.argmin(axis=None. Parameters See ‘numpy. Parameters axis : int. optional Axis along which logical OR is performed out : ndarray. [3]. 2.argmax would return an ndarray.argmax() 11 >>> x. but returns a matrix object where ndarray.argmax. Examples >>> x = np.all(0) matrix([[False.4))).any(axis=None.argmax(axis=None.argmax‘ for complete descriptions See Also: numpy.any for full documentation.

-7].argmin() 11 >>> x. -1. See Also: numpy. but returns a matrix object where ndarray.argmin would return an ndarray. [3]]) matrix. 2]]) >>> x. order=None) Returns the indices that would partition this array. subok=True. Refer to numpy. kind=’quicksort’. 2. ‘A’ means ‘F’ order if all the arrays are Fortran contiguous. and ‘K’ means as close to the order the array elements appear in memory as possible. x matrix([[ 0. ‘safe’. -5.6. cast to a specified type.4))). Parameters dtype : str or dtype Typecode or data-type to which the array is cast. ‘equiv’.argsort for full documentation. order : {‘C’. -2. -9. casting=’unsafe’. ‘A’. Examples >>> x = -np. order=None) Returns the indices that would sort this array.1 See Also: numpy. Standard array subclasses 131 .0. order=’K’. kind=’introselect’. -6.astype(dtype.argsort equivalent function matrix. ‘same_kind’.argmin(1) matrix([[3]. ‘F’.argsort(axis=-1. Default is ‘K’.NumPy Reference. -11]]) >>> x. 2. -10. axis=-1.8. ‘C’ means C order. ‘F’ means Fortran order. ‘K’}. [ -8. optional Controls the memory layout order of the result. casting : {‘no’. ‘C’ order otherwise.argmin. Refer to numpy.argmin(0) matrix([[2. optional 1.reshape((3.argmin Notes This is the same as ndarray. Release 1.argpartition(kth.8. copy=True) Copy of the array. -3].matrix(np. [ -4.argpartition for full documentation.arange(12). [3]. ‘unsafe’}. See Also: numpy.argpartition equivalent function matrix. New in version 1.

optional If True. a. • ‘equiv’ means only byte-order changes are allowed. If this is set to false.astype(t). Parameters inplace : bool. Array objects . swap bytes in-place.real. 132 Chapter 1. Defaults to ‘unsafe’ for backwards compatibility. this is a view to self. 2.5]) >>> x. 2. • ‘same_kind’ means only safe casts or casts within a kind. optional By default. • ‘safe’ means only casts which can preserve values are allowed. 2]) matrix. the input array is returned instead of a copy. • ‘unsafe’ means any data conversions may be done.1 Controls what kind of data casting may occur.array([1. order. optional If True. like float64 to float32. are allowed. . • ‘no’ means the data types should not be cast at all. then sub-classes will be passed-through (default). arr_t is a new array of the same shape as the input array. order given by dtype. 2. one should use Examples >>> x = np. and the dtype.NumPy Reference. astype always returns a newly allocated array. Release 1. 2.byteswap(inplace) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array. Raises ComplexWarning When casting from complex to float or int. subok : bool. To avoid this.8. otherwise the returned array will be forced to be a base-class array. optionally swapped in-place. and subok requirements are satisfied. copy : bool. Returns out : ndarray The byteswapped array. default is False.5]) >>> x array([ 1.astype(int) array([1. . If inplace is True. Returns arr_t : ndarray Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input paramter). 2. order. with dtype.

13090].compress equivalent function matrix. dtype=’|S3’) matrix.choose equivalent function matrix.NumPy Reference. dtype=int16) >>> map(hex. dtype=np. 8755]. out=None) Return selected slices of this array along given axis.1 Examples >>> A = np. Release 1. See Also: numpy. a_max.clip for full documentation.int16) >>> map(hex. 1. 1. ’0x3322’] Arrays of strings are not swapped >>> A = np. Refer to numpy. Refer to numpy. out=None) Return an array whose values are limited to [a_min. mode=’raise’) Use an index array to construct a new array from a set of choices.byteswap() array([’ceg’. See Also: numpy. element-wise.compress(condition.8.array([1. ’0x2233’] >>> A.conjugate equivalent function matrix. ’0x1’. Standard array subclasses 133 . a_max]. See Also: numpy. axis=None. 256. A) [’0x1’.choose for full documentation.array([’ceg’.choose(choices. Refer to numpy. ’fac’]) >>> A. Refer to numpy.conjugate() Return the complex conjugate.clip equivalent function matrix. out=None.conjugate for full documentation. A) [’0x100’. ’fac’].byteswap(True) array([ 256.6.conj() Complex-conjugate all elements. ’0x100’.compress for full documentation.clip(a_min. See Also: numpy.

(Note that this function and :func:numpy.3].1 Refer to numpy.8.conjugate for full documentation.) See Also: numpy.copy.cumprod(axis=None. ‘K’}.5.2. ‘C’ otherwise. ‘F’ means F-order.cumsum(axis=None.cumsum equivalent function 134 Chapter 1. but have different default values for their order= arguments. 5. See Also: numpy. out=None) Return the cumulative sum of the elements along the given axis.NumPy Reference. ‘A’. numpy. out=None) Return the cumulative product of the elements along the given axis. Refer to numpy. ‘C’ means C-order.copy() >>> x. See Also: numpy. ‘K’ means match the layout of a as closely as possible. ‘A’ means ‘F’ if a is Fortran contiguous. 3]. Array objects . 2.copyto Examples >>> x = np. 0.flags[’C_CONTIGUOUS’] True matrix. See Also: numpy.conjugate equivalent function matrix. dtype=None. [4. Release 1. optional Controls the memory layout of the copy. order=’F’) >>> y = x.cumsum for full documentation. dtype=None. [0.[4. ‘F’. 6]]) >>> y.fill(0) >>> x array([[0.copy(order=’C’) Return a copy of the array.copy are very similar. 0]. 0. 0]]) >>> y array([[1.cumprod equivalent function matrix. Parameters order : {‘C’.cumprod for full documentation. Refer to numpy.6]].array([[1.

. axis1=0.load or numpy.. Parameters None matrix. [ 2.dot for full documentation.dot(b) array([[ 2.dot equivalent function Examples >>> a = np.6. pickle. See Also: numpy. [ 8. Standard array subclasses 135 . Parameters value : scalar All elements of a will be assigned this value.diagonal(offset=0. 8.dot(b.].]]) matrix.diagonal for full documentation.NumPy Reference.eye(2) >>> b = np. Release 1. 2...]]) This array method can be conveniently chained: >>> a.dot(b).dot(b) array([[ 8. out=None) Dot product of two arrays.load. 2. Refer to numpy.fill(value) Fill the array with a scalar value.dumps() Returns the pickle of the array as a string. 2)) * 2 >>> a. 8.dump(file) Dump a pickle of the array to the specified file. axis2=1) Return specified diagonals. Examples 1.loads or numpy. See Also: numpy.8. The array can be read back with pickle. Parameters file : str A string naming the dump file.loads will convert the string back to an array. matrix.].1 matrix.diagonal equivalent function matrix. Refer to numpy.ones((2.

1.2]. 1. [3. 7]. 2. Returns y : ndarray A copy of the input array. See Also: ravel Return a flattened array. Examples >>> a = np. Equivalent to np.arange(12). 4]) >>> a. 2.fill(1) >>> a array([ 1. 11]]) >>> x.asarray(self).flatten(order=’C’) Return a copy of the array collapsed into one dimension.array([[1. 4]) matrix. ‘F’. flattened to one dimension. Fortran (column-major) order.reshape((3. x matrix([[ 0..empty(2) >>> a. [ 4.getA() array([[ 0.4]]) >>> a.matrix(np. Release 1. 136 Chapter 1. 6. Array objects . Parameters None Returns ret : ndarray self as an ndarray Examples >>> x = np. 2. 9.]) matrix.1 >>> a = np. Parameters order : {‘C’.array([1.NumPy Reference. 3]. 5. The default is ‘C’. ‘A’}. optional Whether to flatten in C (row-major). 3.flatten() array([1. 3]. 10. 1.fill(0) >>> a array([0. flat A 1-D flat iterator over the array.flatten(’F’) array([1. 3.4))).getA() Return self as an ndarray object. or preserve the C/Fortran ordering from a. 0]) >>> a = np.8. 2. [ 8. 2]) >>> a.

j.size) all return True.eye(self[0. 3].j. 6. 4. [ 8. 6.getA1() Return self as a flattened ndarray. Parameters None Returns ret : matrix object complex conjugate transpose of self Examples >>> x = np. +0. -2.j. 5. [ 1.+11. 8.j. -5.j. 2.getA1() array([ 0.j]. 6. 7].j]. 11. z matrix([[ 0. -7.j].getH() Returns the (complex) conjugate transpose of self. as an ndarray Examples >>> x = np. +4. 9. 10.1 [ 4. -8. 7.j.j. 10. +9. 11]]) >>> x.NumPy Reference. -9. -3. 9. 6. +2. 2. +8. +6.j. [ 8. 10. -4.matrix(np. 1-D.j]]) matrix. -1. 5. 1.j. 2.transpose(self) if self is real-valued.j].j]. 3. 7. 3.getI() Returns the (multiplicative) inverse of invertible self. 11.j. 6. 5. 5.j. 10. [ 3. Release 1. 10. 11]) matrix. +1. Equivalent to np.8. [ 4. 1.j.-10. [ 2. Parameters None Returns ret : matrix object If self is non-singular. 11]]) matrix.reshape((3.arange(12). x matrix([[ 0. +0.reshape((3.-11.arange(12). [ 8.:].asarray(x).j. 5. ret is such that ret * self == self * ret == np.j]]) >>> z.+10. +5. 1. +3.j.6. Standard array subclasses 137 . -6.ravel() Parameters None Returns ret : ndarray self.4))) >>> z = x . 8. 9. 4.j.matrix(np.1j*x. Equivalent to np.j.matrix(np. +7.getH() matrix([[ 0.j. 9.4))). 9. [ 4. 7]. 1. 7.

offset=0) Returns a field of the given array as a certain type. m matrix([[1.8. -0. 4]]) >>> m.inv Examples >>> m = np. If taking a view with a 32-bit integer (4 bytes).]]) matrix.getI() matrix([[-2. See Also: linalg. 4]]) >>> m. 1. A field is a view of the array data with a given data-type. the offset needs to be between 0 and 12 bytes. 0.NumPy Reference. Does not conjugate! For the complex conjugate transpose. [2. Array objects . The values in the view are determined by the given type and the offset into the current array in bytes. 2.matrix(’[1.linalg. getH Examples >>> m = np.. 4]’). [ 0.getfield(dtype.5]]) >>> m. for example an array of dtype complex128 has 16-byte elements. Release 1. use getH. [3. 4]]) matrix. Parameters None Returns ret : matrix object The (non-conjugated) transpose of the matrix. 1.. The offset needs to be such that the view dtype fits in the array dtype. See Also: transpose. Parameters dtype : str or dtype The data type of the view. 2. The dtype size of the view can not be larger than that of the array itself. 3.getT() matrix([[1.1 Raises numpy. 4]’) >>> m matrix([[1. offset : int 138 Chapter 1.getT() Returns the transpose of the matrix.matrix(’[1. 3.LinAlgError: Singular matrix If self is singular. 2]. ]. [3.].5. .getI() * m matrix([[ 1. 3]. [ 1. 2].

item is very similar to a[args].+1. • int_type: this argument is interpreted as a flat index into the array. Examples >>> x = np.j]*2) >>> x[1.NumPy Reference.+0.random.j]]) >>> x. specifying which element to copy and return. 2. 5.float64) array([[ 1.float64.]]) By choosing an offset of 8 bytes we can select the complex part of the array for our view: >>> x. • tuple of int_types: functions as does a single int_type argument.item((0.8.+1.diag([1.6.j]. offset=8) array([[ 1. 7]. Release 1. unless fields are defined..item(3) 2 >>> x.randint(9. the method only works for arrays with one element (a.1 Number of bytes to skip before beginning the element view..].+0. Parameters *args : Arguments (variable number and type) • none: in this case. 4.+4. except.]]) matrix. 1. Standard array subclasses 139 . 3)) >>> x array([[3.j >>> x array([[ 1.item(7) 5 >>> x. a standard Python scalar is returned. 3]. Void arrays return a buffer object for item(). which element is copied into a standard Python scalar object and returned. 0. [ 0.]..item(*args) Copy an element of an array to a standard Python scalar and return it. [8. 1)) 1. in which case a tuple is returned.getfield(np. item() returns a scalar array object because there is no available Python scalar that would not lose information. 1] = 2 + 4. 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. instead of an array scalar.getfield(np.j. [ 0. 2.. 8. except that the argument is interpreted as an nd-index into the array. [2.j. 0. [ 0. 3]]) >>> x. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math. size=(3.size == 1). Examples >>> x = np. 0.

6.max. Also. x matrix([[ 0. and define the last argument as item.4))). 2. 11]]) >>> x. only used in case a is of size 1.matrix(np. 1. The item should be a scalar value and args must select a single item in the array a. but returns a matrix object where ndarray. Notes Compared to indexing syntax.max Notes This is the same as ndarray. 3].itemset(*args) is equivalent to but faster than a[args] = item. Parameters See ‘amax‘ for complete descriptions See Also: amax.itemset((2. 3]]) >>> x. ndarray. [ 8.itemset(4. Examples >>> x = np.random. 10. 9) >>> x array([[3.itemset(*args) Insert scalar into an array (scalar is cast to array’s dtype. 1. [2. 5. 3]. if you must do this. generally this is discouraged: among other problems. the first argument specifies a single array element location. [8. 0) >>> x. size=(3. a. be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration. 2). itemset provides some speed increase for placing a scalar into a particular location in an ndarray. Then. 7]. if possible) There must be at least 1 argument. Release 1. 3)) >>> x array([[3. 9]]) matrix. [2.max(axis=None. [ 4. Array objects .max() 140 Chapter 1. 8. It is either an int or a tuple. However.reshape((3.item((2. 3]. If two arguments: the last argument is the value to be set and must be a scalar.max would return an ndarray. 9. Parameters *args : Arguments If one argument: a scalar. 0. out=None) Return the maximum value along an axis. 7]. [8. 7].NumPy Reference. 2)) 3 matrix.arange(12).8. Examples >>> x = np. when using itemset (and item) inside a loop. it complicates the appearance of the code.randint(9. 5. 5.1 1 >>> x. 1.

8. Parameters See ‘amin‘ for complete descriptions. 10. 3]..mean for full documentation. 11]]) >>> x. out=None) Returns the average of the matrix elements along the given axis.min Notes This is the same as ndarray. -6.min. [ 4. Refer to numpy.min(0) 1.mean except that.mean(axis=None.matrix(np. [11]]) matrix. -7].5]. 4))) >>> x matrix([[ 0. Examples >>> x = -np.4))). 7.mean Notes Same as ndarray. ndarray. 9. x matrix([[ 0. 5.min(axis=None. [ -8.min would return an ndarray.max(1) matrix([[ 3]. Release 1. [ 8. [ -4.mean() 5. this returns a matrix object. See Also: numpy.1 11 >>> x. -5. -9. 7]. [ 7].matrix(np. 6.max(0) matrix([[ 8. Examples >>> x = np. dtype=None.reshape((3. 5. -11]]) >>> x..mean(1) matrix([[ 1. out=None) Return the minimum value along an axis. See Also: amin.]]) >>> x.5 >>> x.min() -11 >>> x.arange(12). where that returns an ndarray. -10. 6.6.NumPy Reference. Standard array subclasses 141 .arange(12). [ 5. [ 9. -3].5]]) matrix. 10.mean(0) matrix([[ 4. -2. -1. 1. 2.5].reshape((3.. but returns a matrix object where ndarray. 11]]) >>> x. 9.

New in version 1.dtype. For example. The code does a case-insensitive check on the first letter of new_order for the alternatives above. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. Release 1.view(arr. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once.native order .8.big endian .little endian . Parameters new_order : string. -11]]) >>> x.nonzero for full documentation.0.ignore (no change to byte order) The default value (‘S’) results in swapping the current byte order.1 matrix([[ -8. [ -7].min(1) matrix([[ -3]. {’>’. Returns new_arr : array New array object with the dtype reflecting given change to the byte order. {’=’. order=None) Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. optional Byte order to force.NumPy Reference. any of ‘B’ or ‘b’ or ‘biggish’ are valid to specify big-endian.8. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. kind=’introselect’. matrix. -10. axis : int. new_order codes can be any of: * * * * * ’S’ {’<’. The order all elements in the partitions is undefined. -9. The ordering of the elements in the two partitions is undefined. See Also: numpy. Array objects . swap ’L’} ’B’} ’N’} ’I’} dtype from current to opposite endian . a value from the byte order specifications above. axis=-1. Parameters kth : int or sequence of ints Element index to partition by.newbyteorder(new_order=’S’) Return the array with the same data viewed with a different byte order. Equivalent to: arr. optional 142 Chapter 1. {’|’.nonzero() Return the indices of the elements that are non-zero.partition(kth. [-11]]) matrix.nonzero equivalent function matrix. Refer to numpy.

2.prod(axis=None. this argument specifies which fields to compare first. 5. second. except.8. 3.4))). 45. Default is ‘introselect’. 2.arange(12). argpartition Indirect partition. which means sort along the last axis. [ 4. order : list. kind : {‘introselect’}. [ 8.NumPy Reference.partition Return a parititioned copy of an array. Release 1. 2.matrix(np. 6. 3) >>> a array([2.prod(1) matrix([[ 0]. [ 840]. 3]. 4]) matrix. 120. 231]]) >>> x. 4]) >>> a. See Also: prod. Examples >>> x = np. Default is -1. Standard array subclasses 143 . Examples >>> a = np.prod Notes Same as ndarray. 7]. 11]]) >>> x. optional Selection algorithm. sort Full sort. 3. 10. 1. this returns a matrix object instead.prod. x matrix([[ 0.prod(0) matrix([[ 0.1 Axis along which to sort.array([3. Refer to prod for full documentation. optional When a is an array with fields defined. 4. Not all fields need be specified. See Also: numpy.reshape((3. where that returns an ndarray.partition(a. 1. 1]) >>> a. 9. etc. out=None) Return the product of the array elements over the given axis.partition for notes on the different algorithms.6. [7920]]) 1. dtype=None.partition((1. Notes See np. ndarray.prod() 0 >>> x. 3)) array([1.

matrix. values. this returns a matrix object. out=None) Peak-to-peak (maximum . 10.repeat(repeats. Examples >>> x = np. mode=’raise’) Set a. 2.ptp Notes Same as ndarray. See Also: numpy.repeat for full documentation.ptp() 11 >>> x.put(indices. [ 4.flat a flat iterator on the array.minimum) value along the given axis.flat[n] = values[n] for all n in indices. 3]. [3]]) matrix. Refer to numpy.put equivalent function matrix.arange(12). axis=None) Repeat elements of an array. Refer to numpy. 8]]) >>> x.8.ptp(axis=None. See Also: numpy.ptp.matrix(np. See Also: numpy. Array objects .ravel for full documentation. 8. [3]. 9.NumPy Reference. See Also: 144 Chapter 1. except.put for full documentation. where that would return an ndarray object.ravel equivalent function ndarray. Release 1.ptp for full documentation. 11]]) >>> x. 7]. Refer to numpy. 5.reshape((3.1 matrix.ravel([order ]) Return a flattened array. 1. Refer to numpy. 8.ptp(1) matrix([[3].ptp(0) matrix([[8. x matrix([[ 0. 6.4))). [ 8.

3]]. Release 1. Only contiguous arrays (data elements consecutive in memory) can be resized. However. Refer to numpy. order=’C’) Returns an array containing the same data with a new shape.reshape(shape. Parameters new_shape : tuple of ints. SystemError If the order keyword argument is specified. 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). 1]. Default is True. 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. refcheck=True) Change shape and size of array in-place. This behaviour is a bug in NumPy.array([[0. resized. and the data memory must be changed.resize(new_shape.repeat equivalent function matrix. Notes This reallocates space for the data area if necessary. See Also: numpy. 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. or n ints Shape of resized array.resize((2.6. 1)) >>> a 1. optional If False. Returns None Raises ValueError If a does not own its own data or references or views to it exist. [2. refcheck : bool. Standard array subclasses 145 . See Also: resize Return a new array with the specified shape.reshape for full documentation.8. reference count will not be checked.1 numpy. and reshaped: >>> a = np.reshape equivalent function matrix. order=’C’) >>> a.NumPy Reference.

1.array([[0. 3]]) >>> b.. [3. [2.. 1)) >>> a array([[0]. For full documentation.resize(2. but missing entries are filled with zeros: >>> b = np.8.searchsorted(v. [2]]) Enlarging an array: as above..setfield(val.around equivalent function matrix.resize((2.round(decimals=0. 0. 0]]) Referencing an array prevents resizing. see numpy. Refer to numpy. side=’left’.around for full documentation. 1].NumPy Reference.searchsorted equivalent function matrix. dtype.. sorter=None) Find indices where elements of v should be inserted in a to maintain order.resize((1. 1).resize((1. Release 1. 3) # new_shape parameter doesn’t have to be a tuple >>> b array([[0. Parameters val : object 146 Chapter 1.. offset=0) Put a value into a specified place in a field defined by a data-type. [1]]) >>> a = np. refcheck=False) >>> a array([[0]]) >>> c array([[0]]) matrix. [2. Array objects . 3]]. >>> c = a >>> a. Unless refcheck is False: >>> a. order=’F’) >>> a. See Also: numpy. ValueError: cannot resize an array that has been referenced . Place val into a‘s field defined by dtype and beginning offset bytes into the field. out=None) Return a with each element rounded to the given number of decimals.1 array([[0]. 1].array([[0.searchsorted See Also: numpy. 2]. 1)) Traceback (most recent call last): ..

int32) array([[3. 0. (The exception for string is made so that unpickling can be done without copying memory.48219694e-323. 0. ALIGNED.NumPy Reference. 1.48219694e-323. Release 1.00000000e+000. 3.setfield(np. 0. [3. 1. 3]. >>> x. uic=None) Set array flags WRITEABLE.. respectively. align=None. 0.48219694e-323. dtype : dtype object Data-type of the field in which to place val. 0.int32) >>> x array([[ 1.].getfield(np.]]) >>> x. 3.setfield(3.6.00000000e+000. Returns None See Also: getfield Examples >>> x = np.float64) array([[ 1. 1. [ 1. np. Standard array subclasses 147 . uic : bool. np. [ 0.eye(3).]]) 1.]..00000000e+000]]) matrix. These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below).. 1.8. 3].48219694e-323.setflags(write=None. optional Describes whether or not a is aligned properly for its type. or is a string. or the ultimate owner of the memory exposes a writeable buffer interface. [ 1...48219694e-323].eye(3) >>> x. align : bool. and UPDATEIFCOPY. offset : int.getfield(np. [3...48219694e-323].]. 1. 1.. [ 0. 1. 3. 0. optional Describes whether or not a can be written to. 1. The UPDATEIFCOPY flag can never be set to True. [ 0. The flag WRITEABLE can only be set to True if the array owns its own memory. optional The number of bytes into the field at which to place val..int32) >>> x.. [ 0. The ALIGNED flag can only be set to True if the data is actually aligned according to the type.. 1.]. 0. 3]]) >>> x array([[ 1.) Parameters write : bool.. optional Describes whether or not a is a copy of another “base” array. 0.1 Value to be placed in field. 1.

Examples >>> y array([[3. [2. second. UPDATEIFCOPY (U) this array is a copy of some other array (referenced by . WRITEABLE (W) the data area can be written to. the base array will be updated with the contents of this array. 1. Default is ‘quicksort’. etc. optional Axis along which to sort. which means sort along the last axis. 9]]) >>> y. [8.1 Notes Array flags provide information about how the memory area used for the array is to be interpreted. All flags can be accessed using their first (upper case) letter as well as the full name. optional Sorting algorithm. 0]. order : list.8. Release 1. ‘heapsort’}. optional When a is an array with fields defined.NumPy Reference. ‘mergesort’. and ALIGNED. When this array is deallocated. order=None) Sort an array. kind : {‘quicksort’. Default is -1.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False UPDATEIFCOPY : False >>> y. in-place. 0.setflags(write=0. 7]. Array objects . only three of which can be changed by the user: UPDATEIFCOPY. Not all fields need be specified.setflags(uic=1) Traceback (most recent call last): File "<stdin>". There are 6 Boolean flags in use. ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler). 148 Chapter 1. in <module> ValueError: cannot set UPDATEIFCOPY flag to True matrix.base). align=0) >>> y. this argument specifies which fields to compare first. kind=’quicksort’. 5.sort(axis=-1. line 1.sort Return a sorted copy of an array. Parameters axis : int. See Also: numpy.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y. WRITEABLE.

Standard array subclasses 149 . dtype=[(’x’. Refer to numpy. Release 1. See Also: numpy. 1. 1)]. partition Partial sort. 1). int)]) >>> a. lexsort Indirect stable sort on multiple keys. (’y’.squeeze for full documentation. 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> a = np.6.std Notes This is the same as ndarray. Notes See sort for notes on the different sorting algorithms. See Also: numpy.std. 3]]) >>> a.std for full documentation.array([(’a’. ’<i4’)]) matrix.squeeze equivalent function matrix. dtype=[(’x’.NumPy Reference. (’y’.4]. Examples >>> a = np. dtype=None. 2)].std(axis=None. [1. ddof=0) Return the standard deviation of the array elements along the given axis. ’S1’).1]]) >>> a. (’a’. out=None.8.squeeze(axis=None) Remove single-dimensional entries from the shape of a. except that where an ndarray would be returned.sort(order=’y’) >>> a array([(’c’. Refer to numpy. 4]. a matrix object is returned instead. [3.sort(axis=1) >>> a array([[1. 3]. 2).1 argsort Indirect sort. (’c’.sort(axis=0) >>> a array([[1. searchsorted Find elements in sorted array. [1.array([[1. ’|S1’).

[ 8.11803399].26598632]]) >>> x.1 Examples >>> x = np. [ 7.].swapaxes(axis1.std(1) matrix([[ 1. 3.]]) >>> out = np. [ 4. [4.sum(axis=1. 3].take for full documentation.std(0) matrix([[ 3.std() 3. 2). [ 1.matrix([[1.matrix(np.arange(12). axis2) Return a view of the array with axis1 and axis2 interchanged.4520525295346629 >>> x. Refer to numpy. 5.26598632.sum Notes This is the same as ndarray. See Also: numpy.sum(axis=1) matrix([[3].sum(axis=1. 9.]. dtype=’float’) matrix([[ 3. a matrix object is returned instead.11803399]. See Also: 150 Chapter 1. [ 7. Refer to numpy. 7]. Release 1.26598632. 4))) >>> x matrix([[ 0.11803399]]) matrix.swapaxes for full documentation.reshape((3. 11]]) >>> x. 2]. Examples >>> x = np.swapaxes equivalent function matrix. 6.]]) matrix. 3. out=out) matrix([[ 3. [7]]) >>> x. dtype=None.sum(axis=None.8. out=None.sum. out=None) Returns the sum of the matrix elements. except that where an ndarray would be returned.sum for full documentation. 1. [ 1.sum() 10 >>> x. Array objects .take(indices. mode=’raise’) Return an array formed from the elements of a at the given indices.zeros((1. See Also: numpy.26598632. 10. 2. 3. Refer to numpy. dtype=’float’) >>> x.NumPy Reference. axis=None. dtype=’float’. along the given axis. 3]]) >>> x.

write(a.tostring(order=’C’) Construct a Python string containing the raw data bytes in the array. Notes This is a convenience function for quick storage of array data.tolist() [[0. 5. 1. [8. x matrix([[ 0. and then using “format” % item. 3]. ‘Any’ order means C-order unless the F_CONTIGUOUS flag in the array is set. See ndarray. 5. 1. [ 8.tolist for full documentation. optional Order of the data for multidimensional arrays: C. 10.4))). Each entry in the array is formatted to text by first converting it to the closest Python type. [ 4. format=”%s”) Write array to a file as text or binary (default). sep=”“.tolist Examples >>> x = np. Data is always written in ‘C’ order. 11]] matrix. Parameters order : {‘C’. 11]]) >>> x.take equivalent function matrix. Information on endianness and precision is lost.6. 1. sep : str Separator between array items for text output. 9.1 numpy. or ‘Any’ order (the default is ‘C’-order). Fortran.arange(12). matrix.8. 2. 3]. [4. 6. so this method is not a good choice for files intended to archive data or transport data between machines with different endianness.matrix(np.tostring()).tolist() Return the matrix as a (possibly nested) list. 9. 10. The data produced by this method can be recovered using the function fromfile(). in which case it means ‘Fortran’ order. equivalent to file. If “” (empty). or the same as for the original array. The string can be produced in either ‘C’ or ‘Fortran’. 2. Constructs a Python string showing a copy of the raw contents of data memory. Release 1.tofile(fid. format : str Format string for text file output. 7]. independent of the order of a. 7]. None}.NumPy Reference. See Also: ndarray. Standard array subclasses 151 . or a string containing a filename. ‘F’. Some of these problems can be overcome by outputting the data as text files. at the expense of speed and file size. a binary file is written. 6. Parameters fid : file or str An open file object.reshape((3.

4]]) >>> a array([[1.tostring(’C’) == x. axis1=0. [3. with axes suitably permuted. or n ints • None or no argument: reverses the order of the axes. For an n-D array. 3]]) >>> x. i[0]). Examples >>> x = np. Array objects .. If axes are not provided and a. . this is the usual matrix transpose.transpose(). Examples >>> a = np.1 Returns s : str A Python string exhibiting a copy of a‘s raw data. out=None) Return the sum along diagonals of the array.array([[1..T Array property returning the array transposed. 1].trace equivalent function matrix. then a. i[n-2]. i[1].transpose()‘s j-th axis. [2. i[1]. 2].tostring(’F’) ’\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00’ matrix. their order indicates how the axes are permuted (see Examples). Parameters axes : None.) For a 2-D array.array([[0. Refer to numpy. if axes are given.tostring() True >>> x.shape = (i[n-1].trace for full documentation. first cast the 1-D array into a matrix object.tostring() ’\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00’ >>> x.trace(offset=0. • 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.NumPy Reference. axis2=1. this has no effect. [3. See Also: numpy.. 4]]) 152 Chapter 1. See Also: ndarray. i[n-2].8. . • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a.transpose(*axes) Returns a view of the array with axes transposed.. 2]. dtype=None. For a 1-D array. i[n-1]). (To change between column and row vectors.shape = (i[0]. tuple of ints. Release 1.

type=None) New view of array with the same data.var for full documentation. a matrix object is returned instead. 6.. e.transpose() array([[1. 4]]) >>> a. ddof=0) Returns the variance of the matrix elements. which then specifies the type of the returned object (this is equivalent to setting the type parameter). 10.matrix(np. The default.25]]) 10. dtype=None.6.var() 11. 3].25]. Parameters dtype : data-type or ndarray sub-class. float32 or int16. optional Data-type descriptor of the returned view. This argument can also be specified as an ndarray sub-class.NumPy Reference. 2. Standard array subclasses 153 . along the given axis.transpose((1. except that where an ndarray would be returned. [ 1. 9.var(0) matrix([[ 10.var.66666667.view() is used two different ways: 1. results in the view having the same data-type as a.66666667. 3]. Refer to numpy. Again. Release 1.view(dtype=None.916666666666666 >>> x. 7]. type : Python type. [ 8. Examples >>> x = np. the default None results in type preservation. 4))) >>> x matrix([[ 0.var Notes This is the same as ndarray. [ 4. 1.reshape((3. Notes a. 5.g. See Also: numpy. 4]]) >>> a. ndarray or matrix. >>> x.8. 3]. [2.1 >>> a..transpose(1. out=None. 11]]) >>> x. 0) array([[1.g.66666667]]) matrix.var(1) matrix([[ 1. [2. optional Type of the returned view. 10. 3]. None.66666667. e. 4]]) matrix.var(axis=None. 10.arange(12). 0)) array([[1.25]. [2. [ 1.

NumPy Reference, Release 1.8.1

a.view(some_dtype) or a.view(dtype=some_dtype) constructs a view of the array’s memory
with a different data-type. 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.
For a.view(some_dtype), if some_dtype has a different number of bytes per entry than the previous dtype (for example, converting a regular array to a structured array), then the behavior of the view
cannot be predicted just from the superficial appearance of a (shown by print(a)). It also depends on
exactly how a is stored in memory. Therefore if a is C-ordered versus fortran-ordered, versus defined as a
slice or transpose, etc., the view may give different results.
Examples
>>> x = np.array([(1, 2)], dtype=[(’a’, np.int8), (’b’, np.int8)])

Viewing array data using a different type and dtype:
>>> y = x.view(dtype=np.int16, type=np.matrix)
>>> y
matrix([[513]], dtype=int16)
>>> print type(y)
<class ’numpy.matrixlib.defmatrix.matrix’>

Creating a view on a structured array so it can be used in calculations
>>> x = np.array([(1, 2),(3,4)], dtype=[(’a’, np.int8), (’b’, np.int8)])
>>> xv = x.view(dtype=np.int8).reshape(-1,2)
>>> xv
array([[1, 2],
[3, 4]], dtype=int8)
>>> xv.mean(0)
array([ 2., 3.])

Making changes to the view changes the underlying array
>>> xv[0,1] = 20
>>> print x
[(1, 20) (3, 4)]

Using a view to convert an array to a record array:
>>> z = x.view(np.recarray)
>>> z.a
array([1], dtype=int8)

Views share data:
>>> x[0] = (9, 10)
>>> z[0]
(9, 10)

Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices,
transposes, fortran-ordering, etc.:
>>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16)
>>> y = x[:, 0:2]
>>> y
array([[1, 2],
[4, 5]], dtype=int16)

154

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> y.view(dtype=[(’width’, np.int16), (’length’, np.int16)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: new type not compatible with array.
>>> z = y.copy()
>>> z.view(dtype=[(’width’, np.int16), (’length’, np.int16)])
array([[(1, 2)],
[(4, 5)]], dtype=[(’width’, ’<i2’), (’length’, ’<i2’)])

numpy.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
>>> x = np.array([[1, 2], [3, 4]])
>>> m = np.asmatrix(x)
>>> x[0,0] = 5
>>> m
matrix([[5, 2],
[3, 4]])

numpy.bmat(obj, ldict=None, gdict=None)
Build a matrix object from a string, nested sequence, or array.
Parameters
obj : str or array_like
Input data. Names of variables in the current scope may be referenced, even if obj is a
string.
Returns
out : matrix
Returns a matrix object, which is a specialized 2-D array.
See Also:
matrix
Examples
>>>
>>>
>>>
>>>

A
B
C
D

=
=
=
=

np.mat(’1
np.mat(’2
np.mat(’3
np.mat(’7

1;
2;
4;
8;

1
2
5
9

1’)
2’)
6’)
0’)

1.6. Standard array subclasses

155

NumPy Reference, Release 1.8.1

All the following expressions construct the same block matrix:
>>> np.bmat([[A, B], [C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat(np.r_[np.c_[A, B], np.c_[C, D]])
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])
>>> np.bmat(’A,B; C,D’)
matrix([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 4, 7, 8],
[5, 6, 9, 0]])

Example 1: Matrix creation from a string
>>> a=mat(’1 2 3; 4 5 3’)
>>> print (a*a.T).I
[[ 0.2924 -0.1345]
[-0.1345 0.0819]]

Example 2: Matrix creation from nested sequence
>>> 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]])

Example 3: Matrix creation from an array
>>> 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]])

1.6.3 Memory-mapped file arrays
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
memmap.flush()

Create a memory-map to an array stored in a binary file on disk.
Write any changes in the array to the file on disk.

class numpy.memmap
Create a memory-map to an array stored in a binary file on disk.
156

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire
file into memory. Numpy’s memmap’s are array-like objects. This differs from Python’s mmap module, which
uses file-like objects.
This subclass of ndarray has some unpleasant interactions with some operations, because it doesn’t quite fit
properly as a subclass. An alternative to using this subclass is to create the mmap object yourself, then create an
ndarray with ndarray.__new__ directly, passing the object created in its ‘buffer=’ parameter.
This class may at some point be turned into a factory function which returns a view into an mmap buffer.
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’
‘r+’
‘w+’
‘c’

Open existing file for reading only.
Open existing file for reading and writing.
Create or overwrite existing file for reading and writing.
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
normally be a multiple of the byte-size of dtype. When mode != ’r’, even positive offsets beyond end of file are valid; The file will be extended to accommodate the
additional data. The default offset is 0.
shape : tuple, optional
The desired shape of the array. If mode == ’r’ and the number of remaining bytes
after offset is not a multiple of the byte-size of dtype, you must specify shape. 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 (columnmajor). 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
>>> data = np.arange(12, dtype=’float32’)
>>> data.resize((3,4))

1.6. Standard array subclasses

157

NumPy Reference, Release 1.8.1

This example uses a temporary file so that doctest doesn’t write files to your directory. You would use a ‘normal’
filename.
>>> from tempfile import mkdtemp
>>> import os.path as path
>>> filename = path.join(mkdtemp(), ’newfile.dat’)

Create a memmap with dtype and shape that matches our data:
>>> fp = np.memmap(filename, dtype=’float32’, mode=’w+’, shape=(3,4))
>>> fp
memmap([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]], dtype=float32)

Write data to memmap array:
>>> fp[:] = data[:]
>>> fp
memmap([[ 0.,
1.,
[ 4.,
5.,
[ 8.,
9.,

2.,
6.,
10.,

3.],
7.],
11.]], dtype=float32)

>>> fp.filename == path.abspath(filename)
True

Deletion flushes memory changes to disk before removing the object:
>>> del fp

Load the memmap and verify data was stored:
>>> newfp = np.memmap(filename, dtype=’float32’, mode=’r’, shape=(3,4))
>>> newfp
memmap([[ 0.,
1.,
2.,
3.],
[ 4.,
5.,
6.,
7.],
[ 8.,
9., 10., 11.]], dtype=float32)

Read-only memmap:
>>> fpr = np.memmap(filename, dtype=’float32’, mode=’r’, shape=(3,4))
>>> fpr.flags.writeable
False

Copy-on-write memmap:
>>> fpc = np.memmap(filename, dtype=’float32’, mode=’c’, shape=(3,4))
>>> fpc.flags.writeable
True

It’s 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.,
[ 4.,
5.,
[ 8.,
9.,
>>> fpc[0,:] = 0
>>> fpc
memmap([[ 0.,
0.,

158

2.,
6.,
10.,

0.,

3.],
7.],
11.]], dtype=float32)

0.],

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

[
[

4.,
8.,

5.,
9.,

6.,
10.,

7.],
11.]], dtype=float32)

2.,
6.,
10.,

3.],
7.],
11.]], dtype=float32)

File on disk is unchanged:
>>> fpr
memmap([[
[
[

0.,
4.,
8.,

1.,
5.,
9.,

Offset into a memmap:
>>> fpo = np.memmap(filename, dtype=’float32’, mode=’r’, offset=16)
>>> fpo
memmap([ 4.,
5.,
6.,
7.,
8.,
9., 10., 11.], dtype=float32)

Attributes
filename
offset
mode

(str) Path to the mapped file.
(int) Offset position in the file.
(str) File mode.

Methods
flush()

Write any changes in the array to the file on disk.

memmap.flush()
Write any changes in the array to the file on disk.
For further information, see memmap.
Parameters
None
See Also:
memmap
close

Close the memmap file.

memmap.flush()
Write any changes in the array to the file on disk.
For further information, see memmap.
Parameters
None
See Also:
memmap
Example:
>>> a = memmap(’newfile.dat’, dtype=float, mode=’w+’, shape=1000)
>>> a[10] = 10.0
>>> a[30] = 30.0
>>> del a
>>> b = fromfile(’newfile.dat’, dtype=float)
>>> print b[10], b[30]
10.0 30.0

1.6. Standard array subclasses

159

NumPy Reference, Release 1.8.1

>>> a = memmap(’newfile.dat’, dtype=float)
>>> print a[10], a[30]
10.0 30.0

1.6.4 Character arrays (numpy.char)
See Also:
Creating character arrays (numpy.char)
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.
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
core.defchararray.array(obj[, itemsize, ...])

Provides a convenient view on arrays of string and unicode values.
Create a chararray.

class numpy.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 constructor 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

160

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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.
buffer : int, optional
Memory address of the start of the array data. Default is None, in which case a new
array is created.
offset : int, optional
Fixed stride displacement from the beginning of an axis? Default is 0. Needs to be >=0.
strides : array_like of ints, optional
Strides for the array (see ndarray.strides for full description). Default is None.
order : {‘C’, ‘F’}, optional
The order in which the array data is stored in memory: ‘C’ -> “row major” order (the
default), ‘F’ -> “column major” (Fortran) order.
Examples
>>> charar = np.chararray((3, 3))
>>> charar[:] = ’a’
>>> charar
chararray([[’a’, ’a’, ’a’],
[’a’, ’a’, ’a’],
[’a’, ’a’, ’a’]],
dtype=’|S1’)
>>> charar = np.chararray(charar.shape, itemsize=5)
>>> charar[:] = ’abc’
>>> charar
chararray([[’abc’, ’abc’, ’abc’],
[’abc’, ’abc’, ’abc’],
[’abc’, ’abc’, ’abc’]],
dtype=’|S5’)

Attributes
T
base
ctypes
data
dtype
flags
flat
imag
itemsize
nbytes
ndim
real
shape
size
strides

Same as self.transpose(), except that self is returned if self.ndim < 2.
Base object if memory is from some other object.
An object to simplify the interaction of the array with the ctypes module.
Python buffer object pointing to the start of the array’s data.
Data-type of the array’s elements.
Information about the memory layout of the array.
A 1-D iterator over the array.
The imaginary part of the array.
Length of one array element in bytes.
Total bytes consumed by the elements of the array.
Number of array dimensions.
The real part of the array.
Tuple of array dimensions.
Number of elements in the array.
Tuple of bytes to step in each dimension when traversing an array.

1.6. Standard array subclasses

161

NumPy Reference, Release 1.8.1

chararray.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.])

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

Slicing creates a view, whose memory is shared with x:
>>> y = x[2:]
>>> y.base is x
True

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

162

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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.
self.shape_as(ctypes.c_short).

For example:

•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
>>> import ctypes
>>> x
array([[0, 1],
[2, 3]])
>>> x.ctypes.data
30439712
>>> 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>

chararray.data
Python buffer object pointing to the start of the array’s data.

1.6. Standard array subclasses

163

NumPy Reference, Release 1.8.1

chararray.dtype
Data-type of the array’s 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’>

chararray.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
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.
Arrays can be both C-style and Fortran-style contiguous simultaneously. This is clear for 1-dimensional
arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension arr.strides[dim] may be arbitrary if arr.shape[dim] == 1 or the array has no elements. It does not generally hold that
self.strides[-1] == self.itemsize for C-style contiguous arrays or self.strides[0]
== self.itemsize for Fortran-style contiguous arrays is true.

164

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

Attributes
C_CONTIGUOUS
The data is in a single, C-style contiguous segment.
(C)
F_CONTIGUOUS
The data is in a single, Fortran-style contiguous segment.
(F)
OWNThe array owns the memory it uses or borrows it from another object.
DATA
(O)
WRITEThe data area can be written to. Setting this to False locks the data, making it read-only.
ABLE
A view (slice, etc.) inherits WRITEABLE from its base array at creation time, but a
(W)
view of a writeable array may be subsequently locked while the base array remains
writeable. (The opposite is not true, in that a view of a locked array may not be made
writeable. However, currently, locking a base object does not lock any views that
already reference it, so under that circumstance it is possible to alter the contents of a
locked array via a previously created writeable view onto it.) Attempting to change a
non-writeable array raises a RuntimeError exception.
ALIGNED
The data and all elements are aligned appropriately for the hardware.
(A)
UPThis array is a copy of some other array. When this array is deallocated, the base array
DATEIFwill be updated with the contents of this array.
COPY
(U)
FNC
F_CONTIGUOUS and not C_CONTIGUOUS.
FORC
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
BEHAVED ALIGNED and WRITEABLE.
(B)
CARRAY
BEHAVED and C_CONTIGUOUS.
(CA)
FARRAY
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
(FA)
chararray.flat
A 1-D iterator over the array.
This is a numpy.flatiter instance, which acts similarly to, but is not a subclass of, Python’s built-in
iterator object.
See Also:
flatten
Return a copy of the array collapsed into one dimension.
flatiter
Examples
>>> x = np.arange(1, 7).reshape(2, 3)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x.flat[3]
4
>>> x.T
array([[1, 4],
[2, 5],
[3, 6]])

1.6. Standard array subclasses

165

NumPy Reference, Release 1.8.1

>>> x.T.flat[3]
5
>>> type(x.flat)
<type ’numpy.flatiter’>

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]])

chararray.imag
The imaginary part of the array.
Examples
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.imag
array([ 0.
, 0.70710678])
>>> x.imag.dtype
dtype(’float64’)

chararray.itemsize
Length of one array element in bytes.
Examples
>>>
>>>
8
>>>
>>>
16

x = np.array([1,2,3], dtype=np.float64)
x.itemsize
x = np.array([1,2,3], dtype=np.complex128)
x.itemsize

chararray.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
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480

chararray.ndim
Number of array dimensions.
Examples
>>> x = np.array([1, 2, 3])
>>> x.ndim
1

166

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> y = np.zeros((2, 3, 4))
>>> y.ndim
3

chararray.real
The real part of the array.
See Also:
numpy.real
equivalent function
Examples
>>> x = np.sqrt([1+0j, 0+1j])
>>> x.real
array([ 1.
, 0.70710678])
>>> x.real.dtype
dtype(’float64’)

chararray.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
>>> x = np.array([1, 2, 3, 4])
>>> x.shape
(4,)
>>> y = np.zeros((2, 3, 4))
>>> y.shape
(2, 3, 4)
>>> y.shape = (3, 8)
>>> y
array([[ 0., 0., 0., 0., 0., 0., 0.,
[ 0., 0., 0., 0., 0., 0., 0.,
[ 0., 0., 0., 0., 0., 0., 0.,
>>> y.shape = (3, 6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: total size of new array must be

0.],
0.],
0.]])

unchanged

chararray.size
Number of elements in the array.
Equivalent to np.prod(a.shape), i.e., the product of the array’s dimensions.
Examples
>>> x = np.zeros((3, 5, 2), dtype=np.complex128)
>>> x.size
30
>>> np.prod(x.shape)
30

1.6. Standard array subclasses

167

NumPy Reference, Release 1.8.1

chararray.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:
offset = sum(np.array(i) * a.strides)

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
>>> y = np.reshape(np.arange(2*3*4), (2,3,4))
>>> y
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]]])
>>> y.strides
(48, 16, 4)
>>> y[1,1,1]
17
>>> offset=sum(y.strides * np.array((1,1,1)))
>>> offset/y.itemsize
17
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3,5,2,2])
>>> offset = sum(i * x.strides)
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813

Methods
astype(dtype[, order, casting, subok, copy])
copy([order])

168

Copy of the array, cast to a specified type.
Return a copy of the array.

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

count(sub[, start, end])
decode([encoding, errors])
dump(file)
dumps()
encode([encoding, errors])
endswith(suffix[, start, end])
expandtabs([tabsize])
fill(value)
find(sub[, start, end])
flatten([order])
getfield(dtype[, offset])
index(sub[, start, end])
isalnum()
isalpha()
isdecimal()
isdigit()
islower()
isnumeric()
isspace()
istitle()
isupper()
item(*args)
join(seq)
ljust(width[, fillchar])
lower()
lstrip([chars])
nonzero()
put(indices, values[, mode])
ravel([order])
repeat(repeats[, axis])
replace(old, new[, count])
reshape(shape[, order])
resize(new_shape[, refcheck])
rfind(sub[, start, end])
rindex(sub[, start, end])
rjust(width[, fillchar])
rsplit([sep, maxsplit])
rstrip([chars])
searchsorted(v[, side, sorter])
setfield(val, dtype[, offset])
setflags([write, align, uic])
sort([axis, kind, order])
split([sep, maxsplit])
splitlines([keepends])
squeeze([axis])
startswith(prefix[, start, end])
strip([chars])
swapaxes(axis1, axis2)
swapcase()
take(indices[, axis, out, mode])

1.6. Standard array subclasses

Table 1.45 – continued
Returns an array with the number of non-overlapping occurrences of substring sub in
Calls str.decode element-wise.
Dump a pickle of the array to the specified file.
Returns the pickle of the array as a string.
Calls str.encode element-wise.
Returns a boolean array which is True where the string element
Return a copy of each string element where all tab characters are replaced by one or m
Fill the array with a scalar value.
For each element, return the lowest index in the string where substring sub is found.
Return a copy of the array collapsed into one dimension.
Returns a field of the given array as a certain type.
Like find, but raises ValueError when the substring is not found.
Returns true for each element if all characters in the string are alphanumeric and there
Returns true for each element if all characters in the string are alphabetic and there is
For each element in self, return True if there are only
Returns true for each element if all characters in the string are digits and there is at lea
Returns true for each element if all cased characters in the string are lowercase and th
For each element in self, return True if there are only
Returns true for each element if there are only whitespace characters in the string and
Returns true for each element if the element is a titlecased string and there is at least o
Returns true for each element if all cased characters in the string are uppercase and th
Copy an element of an array to a standard Python scalar and return it.
Return a string which is the concatenation of the strings in the sequence seq.
Return an array with the elements of self left-justified in a string of length width.
Return an array with the elements of self converted to lowercase.
For each element in self, return a copy with the leading characters removed.
Return the indices of the elements that are non-zero.
Set a.flat[n] = values[n] for all n in indices.
Return a flattened array.
Repeat elements of an array.
For each element in self, return a copy of the string with all occurrences of substring o
Returns an array containing the same data with a new shape.
Change shape and size of array in-place.
For each element in self, return the highest index in the string where substring sub is f
Like rfind, but raises ValueError when the substring sub is
Return an array with the elements of self right-justified in a string of length width.
For each element in self, return a list of the words in the string, using sep as the delim
For each element in self, return a copy with the trailing characters removed.
Find indices where elements of v should be inserted in a to maintain order.
Put a value into a specified place in a field defined by a data-type.
Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively.
Sort an array, in-place.
For each element in self, return a list of the words in the string, using sep as the delim
For each element in self, return a list of the lines in the element, breaking at line boun
Remove single-dimensional entries from the shape of a.
Returns a boolean array which is True where the string element
For each element in self, return a copy with the leading and trailing characters remove
Return a view of the array with axis1 and axis2 interchanged.
For each element in self, return a copy of the string with uppercase characters convert
Return an array formed from the elements of a at the given indices.

169

NumPy Reference, Release 1.8.1

title()
tofile(fid[, sep, format])
tolist()
tostring([order])
translate(table[, deletechars])
transpose(*axes)
upper()
view([dtype, type])
zfill(width)

Table 1.45 – continued
For each element in self, return a titlecased version of the string: words start with upp
Write array to a file as text or binary (default).
Return the array as a (possibly nested) list.
Construct a Python string containing the raw data bytes in the array.
For each element in self, return a copy of the string where all characters occurring in t
Returns a view of the array with axes transposed.
Return an array with the elements of self converted to uppercase.
New view of array with the same data.
Return the numeric string left-filled with zeros in a string of length width.

chararray.astype(dtype, order=’K’, casting=’unsafe’, subok=True, copy=True)
Copy of the array, cast to a specified type.
Parameters
dtype : str or dtype
Typecode or data-type to which the array is cast.
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
Controls the memory layout order of the result. ‘C’ means C order, ‘F’ means Fortran
order, ‘A’ means ‘F’ order if all the arrays are Fortran contiguous, ‘C’ order otherwise,
and ‘K’ means as close to the order the array elements appear in memory as possible.
Default is ‘K’.
casting : {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional
Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.
• ‘no’ means the data types should not be cast at all.
• ‘equiv’ means only byte-order changes are allowed.
• ‘safe’ means only casts which can preserve values are allowed.
• ‘same_kind’ means only safe casts or casts within a kind, like float64 to float32, are
allowed.
• ‘unsafe’ means any data conversions may be done.
subok : bool, optional
If True, then sub-classes will be passed-through (default), otherwise the returned array
will be forced to be a base-class array.
copy : bool, optional
By default, astype always returns a newly allocated array. If this is set to false, and the
dtype, order, and subok requirements are satisfied, the input array is returned instead
of a copy.
Returns
arr_t : ndarray
Unless copy is False and the other conditions for returning the input array are satisfied
(see description for copy input paramter), arr_t is a new array of the same shape as the
input array, with dtype, order given by dtype, order.
Raises
ComplexWarning
170

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

When casting from complex to float or int.
a.real.astype(t).

To avoid this, one should use

Examples
>>> x = np.array([1, 2, 2.5])
>>> x
array([ 1. , 2. , 2.5])
>>> x.astype(int)
array([1, 2, 2])

chararray.copy(order=’C’)
Return a copy of the array.
Parameters
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional
Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’
means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as
closely as possible. (Note that this function and :func:numpy.copy are very similar, but
have different default values for their order= arguments.)
See Also:
numpy.copy, numpy.copyto
Examples
>>> x = np.array([[1,2,3],[4,5,6]], order=’F’)
>>> 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

chararray.count(sub, start=0, end=None)
Returns an array with the number of non-overlapping occurrences of substring sub in the range [start,
end].
See Also:
char.count
chararray.decode(encoding=None, errors=None)
Calls str.decode element-wise.
See Also:
char.decode

1.6. Standard array subclasses

171

NumPy Reference, Release 1.8.1

chararray.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.
chararray.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
chararray.encode(encoding=None, errors=None)
Calls str.encode element-wise.
See Also:
char.encode
chararray.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
chararray.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
chararray.fill(value)
Fill the array with a scalar value.
Parameters
value : scalar
All elements of a will be assigned this value.
Examples
>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([ 1., 1.])

chararray.find(sub, start=0, end=None)
For each element, return the lowest index in the string where substring sub is found.
See Also:
char.find
chararray.flatten(order=’C’)
Return a copy of the array collapsed into one dimension.

172

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

Parameters
order : {‘C’, ‘F’, ‘A’}, optional
Whether to flatten in C (row-major), Fortran (column-major) order, or preserve the
C/Fortran ordering from a. 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
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten(’F’)
array([1, 3, 2, 4])

chararray.getfield(dtype, offset=0)
Returns a field of the given array as a certain type.
A field is a view of the array data with a given data-type. The values in the view are determined by the
given type and the offset into the current array in bytes. The offset needs to be such that the view dtype fits
in the array dtype; for example an array of dtype complex128 has 16-byte elements. If taking a view with
a 32-bit integer (4 bytes), the offset needs to be between 0 and 12 bytes.
Parameters
dtype : str or dtype
The data type of the view. The dtype size of the view can not be larger than that of the
array itself.
offset : int
Number of bytes to skip before beginning the element view.
Examples
>>> x = np.diag([1.+1.j]*2)
>>> x[1, 1] = 2 + 4.j
>>> x
array([[ 1.+1.j, 0.+0.j],
[ 0.+0.j, 2.+4.j]])
>>> x.getfield(np.float64)
array([[ 1., 0.],
[ 0., 2.]])

By choosing an offset of 8 bytes we can select the complex part of the array for our view:
>>> x.getfield(np.float64, offset=8)
array([[ 1., 0.],
[ 0., 4.]])

1.6. Standard array subclasses

173

NumPy Reference, Release 1.8.1

chararray.index(sub, start=0, end=None)
Like find, but raises ValueError when the substring is not found.
See Also:
char.index
chararray.isalnum()
Returns true for each element if all characters in the string are alphanumeric and there is at least one
character, false otherwise.
See Also:
char.isalnum
chararray.isalpha()
Returns true for each element if all characters in the string are alphabetic and there is at least one character,
false otherwise.
See Also:
char.isalpha
chararray.isdecimal()
For each element in self, return True if there are only decimal characters in the element.
See Also:
char.isdecimal
chararray.isdigit()
Returns true for each element if all characters in the string are digits and there is at least one character,
false otherwise.
See Also:
char.isdigit
chararray.islower()
Returns true for each element if all cased characters in the string are lowercase and there is at least one
cased character, false otherwise.
See Also:
char.islower
chararray.isnumeric()
For each element in self, return True if there are only numeric characters in the element.
See Also:
char.isnumeric
chararray.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
chararray.istitle()
Returns true for each element if the element is a titlecased string and there is at least one character, false
otherwise.
See Also:

174

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

char.istitle
chararray.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
chararray.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 Python’s optimized math.
Examples
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[3, 1, 7],
[2, 8, 3],
[8, 5, 3]])
>>> x.item(3)
2
>>> x.item(7)
5
>>> x.item((0, 1))
1
>>> x.item((2, 2))
3

chararray.join(seq)
Return a string which is the concatenation of the strings in the sequence seq.
See Also:
char.join

1.6. Standard array subclasses

175

NumPy Reference, Release 1.8.1

chararray.ljust(width, fillchar=’ ‘)
Return an array with the elements of self left-justified in a string of length width.
See Also:
char.ljust
chararray.lower()
Return an array with the elements of self converted to lowercase.
See Also:
char.lower
chararray.lstrip(chars=None)
For each element in self, return a copy with the leading characters removed.
See Also:
char.lstrip
chararray.nonzero()
Return the indices of the elements that are non-zero.
Refer to numpy.nonzero for full documentation.
See Also:
numpy.nonzero
equivalent function
chararray.put(indices, values, mode=’raise’)
Set a.flat[n] = values[n] for all n in indices.
Refer to numpy.put for full documentation.
See Also:
numpy.put
equivalent function
chararray.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.
chararray.repeat(repeats, axis=None)
Repeat elements of an array.
Refer to numpy.repeat for full documentation.
See Also:
numpy.repeat
equivalent function

176

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

chararray.replace(old, new, count=None)
For each element in self, return a copy of the string with all occurrences of substring old replaced by new.
See Also:
char.replace
chararray.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
chararray.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:

1.6. Standard array subclasses

177

NumPy Reference, Release 1.8.1

>>> a = np.array([[0, 1], [2, 3]], order=’C’)
>>> a.resize((2, 1))
>>> a
array([[0],
[1]])
>>> a = np.array([[0, 1], [2, 3]], order=’F’)
>>> a.resize((2, 1))
>>> a
array([[0],
[2]])

Enlarging an array: as above, but missing entries are filled with zeros:
>>> b = np.array([[0, 1], [2, 3]])
>>> b.resize(2, 3) # new_shape parameter doesn’t have to be a tuple
>>> b
array([[0, 1, 2],
[3, 0, 0]])

Referencing an array prevents resizing...
>>> c = a
>>> a.resize((1, 1))
Traceback (most recent call last):
...
ValueError: cannot resize an array that has been referenced ...

Unless refcheck is False:
>>> a.resize((1, 1), refcheck=False)
>>> a
array([[0]])
>>> c
array([[0]])

chararray.rfind(sub, start=0, end=None)
For each element in self, return the highest index in the string where substring sub is found, such that sub
is contained within [start, end].
See Also:
char.rfind
chararray.rindex(sub, start=0, end=None)
Like rfind, but raises ValueError when the substring sub is not found.
See Also:
char.rindex
chararray.rjust(width, fillchar=’ ‘)
Return an array with the elements of self right-justified in a string of length width.
See Also:
char.rjust
chararray.rsplit(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:

178

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

char.rsplit
chararray.rstrip(chars=None)
For each element in self, return a copy with the trailing characters removed.
See Also:
char.rstrip
chararray.searchsorted(v, side=’left’, sorter=None)
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
chararray.setfield(val, dtype, offset=0)
Put a value into a specified place in a field defined by a data-type.
Place val into a‘s field defined by dtype and beginning offset bytes into the field.
Parameters
val : object
Value to be placed in field.
dtype : dtype object
Data-type of the field in which to place val.
offset : int, optional
The number of bytes into the field at which to place val.
Returns
None
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.00000000e+000,
[ 1.48219694e-323,
1.48219694e-323,
>>> x.setfield(np.eye(3), np.int32)
>>> x
array([[ 1., 0., 0.],

1.6. Standard array subclasses

1.48219694e-323],
1.48219694e-323],
1.00000000e+000]])

179

NumPy Reference, Release 1.8.1

[ 0.,
[ 0.,

1.,
0.,

0.],
1.]])

chararray.setflags(write=None, align=None, uic=None)
Set array flags WRITEABLE, ALIGNED, and UPDATEIFCOPY, respectively.
These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below).
The ALIGNED flag can only be set to True if the data is actually aligned according to the type. The
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, 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
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

180

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> y.setflags(uic=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot set UPDATEIFCOPY flag to True

chararray.sort(axis=-1, kind=’quicksort’, order=None)
Sort an array, in-place.
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.
partition
Partial sort.
Notes
See sort for notes on the different sorting algorithms.
Examples
>>> a = np.array([[1,4], [3,1]])
>>> a.sort(axis=1)
>>> a
array([[1, 4],
[1, 3]])
>>> a.sort(axis=0)
>>> a
array([[1, 3],
[1, 4]])

Use the order keyword to specify a field to use when sorting a structured array:
>>> a = np.array([(’a’, 2), (’c’, 1)], dtype=[(’x’, ’S1’), (’y’, int)])
>>> a.sort(order=’y’)
>>> a
array([(’c’, 1), (’a’, 2)],
dtype=[(’x’, ’|S1’), (’y’, ’<i4’)])

1.6. Standard array subclasses

181

NumPy Reference, Release 1.8.1

chararray.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
chararray.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
chararray.squeeze(axis=None)
Remove single-dimensional entries from the shape of a.
Refer to numpy.squeeze for full documentation.
See Also:
numpy.squeeze
equivalent function
chararray.startswith(prefix, start=0, end=None)
Returns a boolean array which is True where the string element in self starts with prefix, otherwise False.
See Also:
char.startswith
chararray.strip(chars=None)
For each element in self, return a copy with the leading and trailing characters removed.
See Also:
char.strip
chararray.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
chararray.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
chararray.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:

182

Chapter 1. Array objects

Return a copy of the array data as a (nested) Python list.tolist() 2] a = np. Data items are converted to the nearest compatible Python type.tostring()). 2]) a. Release 1. Standard array subclasses 183 . sep=”“. [3.tofile(fid.tolist() Return the array as a (possibly nested) list. a = np. Parameters none Returns y : list The possibly nested list of array elements.8. at the expense of speed and file size. or a string containing a filename.array(a. so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Notes This is a convenience function for quick storage of array data. a binary file is written. all remaining cased characters are lowercase.array([[1. sep : str Separator between array items for text output.1 numpy. Examples >>> >>> [1.title() For each element in self.tolist()). The data produced by this method can be recovered using the function fromfile(). format=”%s”) Write array to a file as text or binary (default).6.NumPy Reference.array([1. Notes The array may be recreated. chararray. return a titlecased version of the string: words start with uppercase characters. 2]. See Also: char. format : str Format string for text file output. Data is always written in ‘C’ order.take equivalent function chararray. Some of these problems can be overcome by outputting the data as text files. and then using “format” % item.write(a. Parameters fid : file or str An open file object. Information on endianness and precision is lost. If “” (empty). independent of the order of a.title chararray. equivalent to file. >>> a = np. Each entry in the array is formatted to text by first converting it to the closest Python type. 4]]) 1.

2]). 2]. Fortran. . this is the usual matrix transpose. first cast the 1-D array into a matrix object. 4])] >>> a.) For a 2-D array. return a copy of the string where all characters occurring in the optional argument deletechars are removed. ‘Any’ order means C-order unless the F_CONTIGUOUS flag in the array is set. [3. Release 1.array([[0. i[0]). • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a. • n ints: same as an n-tuple of the same ints (this form is intended simply as a “convenience” alternative to the tuple form) 184 Chapter 1. Examples >>> x = np. or the same as for the original array. array([3.shape = (i[0]. or n ints • None or no argument: reverses the order of the axes. or ‘Any’ order (the default is ‘C’-order). Parameters axes : None. Returns s : str A Python string exhibiting a copy of a‘s raw data.transpose(). tuple of ints. Constructs a Python string showing a copy of the raw contents of data memory.tostring(’C’) == x. If axes are not provided and a. 3]]) >>> x. and the remaining characters have been mapped through the given translation table.shape = (i[n-1]. this has no effect. The string can be produced in either ‘C’ or ‘Fortran’..NumPy Reference.tostring() True >>> x. . then a.. [2. See Also: char. None}.transpose()‘s j-th axis.. i[n-2]. Array objects . ‘F’.translate chararray. in which case it means ‘Fortran’ order. if axes are given.transpose(*axes) Returns a view of the array with axes transposed. For a 1-D array. For an n-D array. 4]] chararray.tostring() ’\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00’ >>> x.8.tostring(’F’) ’\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00’ chararray. their order indicates how the axes are permuted (see Examples).1 >>> list(a) [array([1. Parameters order : {‘C’. deletechars=None) For each element in self..translate(table. 1].tostring(order=’C’) Construct a Python string containing the raw data bytes in the array. i[n-1]). optional Order of the data for multidimensional arrays: C. i[1].tolist() [[1. (To change between column and row vectors. i[1]. i[n-2].

See Also: ndarray. then the behavior of the view 1.NumPy Reference. which then specifies the type of the returned object (this is equivalent to setting the type parameter).1 Returns out : ndarray View of a. 2]. 4]]) >>> a array([[1. results in the view having the same data-type as a. [2. Standard array subclasses 185 . For a. 3]. the default None results in type preservation. 4]]) >>> a. dtype.g.transpose((1. type=None) New view of array with the same data. 4]]) chararray.transpose() array([[1.upper chararray.view(ndarray_subclass) or a. This argument can also be specified as an ndarray sub-class..8. with axes suitably permuted. float32 or int16. Again. This can cause a reinterpretation of the bytes of memory. [3. [3. See Also: char. Examples >>> a = np. [2.transpose(1. Notes a.view(dtype=None.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type. 4]]) >>> a.view(some_dtype). e. a. etc.view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape. 3].view(some_dtype) or a.array([[1. None.6. e. [2.view() is used two different ways: a. Parameters dtype : data-type or ndarray sub-class. 3]. optional Data-type descriptor of the returned view. optional Type of the returned view. 0)) array([[1.T Array property returning the array transposed.. converting a regular array to a structured array). if some_dtype has a different number of bytes per entry than the previous dtype (for example.upper() Return an array with the elements of self converted to uppercase. ndarray or matrix.) This does not cause a reinterpretation of the memory. 2]. The default. type : Python type. 0) array([[1.g. 4]]) >>> a. Release 1.

dtype=[(’a’.copy() >>> z. 4)] Using a view to convert an array to a record array: >>> z = x.. 0:2] >>> y array([[1.NumPy Reference.]) Making changes to the view changes the underlying array >>> xv[0.int16)]) array([[(1.1 cannot be predicted just from the superficial appearance of a (shown by print(a)).: >>> x = np. 4]]. etc.int16). 3. 20) (3.2.mean(0) array([ 2.2) >>> xv array([[1. Array objects . Therefore if a is C-ordered versus fortran-ordered.int8). np. 2)]. dtype=int8) Views share data: >>> x[0] = (9. 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices.int16)]) Traceback (most recent call last): File "<stdin>". 10) >>> z[0] (9.int16) >>> y = x[:. >>> z = y. dtype=int8) >>> xv. 2].int8)]) >>> xv = x..int8). type=np.3].matrix’> Creating a view on a structured array so it can be used in calculations >>> x = np. dtype=[(’width’. the view may give different results. [4. np. (’length’. dtype=np.view(np. in <module> ValueError: new type not compatible with array. It also depends on exactly how a is stored in memory.view(dtype=np.8. np. versus defined as a slice or transpose.reshape(-1. fortran-ordering. line 1. np.matrixlib. 2]. ’<i2’)]) 186 Chapter 1. np.view(dtype=[(’width’.6]]. 5)]].array([[1. 2)].1] = 20 >>> print x [(1.matrix) >>> y matrix([[513]].view(dtype=[(’width’.int8)]) Viewing array data using a different type and dtype: >>> y = x.int16). [3. np. (’length’.defmatrix.view(dtype=np. dtype=int16) >>> print type(y) <class ’numpy.array([(1. Examples >>> x = np. transposes. 5]].int16. np.a array([1]. ’<i2’).recarray) >>> z. dtype=int16) >>> y. (’b’.5.array([(1.[4.int8).(3. dtype=[(’a’. Release 1. np. 2). (’b’. (’length’. [(4.4)]. etc.

).comparison operators automatically remove whitespace from the end when comparing values 3. +.g. 1.8. Note: This class is provided for numarray backward-compatibility. Versus a regular Numpy array of type str or unicode.endswith) and infix operators (e.zfill(width) Return the numeric string left-filled with zeros in a string of length width.char for fast vectorized string operations instead. Otherwise. unicode : bool. order. when false only 8-bit characters. the resulting chararray can contain Unicode characters. unicode=None. *. If order is ‘A’. Standard array subclasses 187 . optional itemsize is the number of characters per scalar in the resulting array. then the object is copied.g. If order is ‘F’.vectorized string operations are provided as methods (e. optional When true. etc. If itemsize is provided and obj is of type str or unicode. then the returned array will be in Fortran-contiguous order (first-index varies the fastest). %) Parameters obj : array of str or unicode-like itemsize : int. New code (not concerned with numarray compatibility) should use arrays of type string_ or unicode_ and use the free functions in numpy. • an ndarray of type str or unicode • a Python str or unicode object. or even discontiguous).array(obj. then the unicode setting of the output array will be automatically determined. See Also: char. ‘A’}. str. a copy will only be made if __array__ returns a copy.1 chararray. copy : bool. If itemsize is None.6. copy=True.NumPy Reference. and obj is an object array or a Python list.zfill argsort numpy. If unicode is None and obj is one of the following: • a chararray. if obj is a nested sequence.values automatically have whitespace removed from the end when indexed 2. then the obj string will be chunked into itemsize pieces. itemsize=None. this class adds the following functionality: 1. order=None) Create a chararray. Release 1.core. optional If true (default). order : {‘C’. optional Specify the order of the array. unicode. Fortran-contiguous. then the array will be in Ccontiguous order (last-index varies the fastest). then the returned array may be in any order (either C-. If order is ‘C’ (default). ‘F’. the itemsize will be automatically determined. or if a copy is needed to satisfy any of the other requirements (itemsize.defchararray.

aligned and byteorder. and a corresponding scalar data type object record. Note that formats must be a list. float. a new array is created of the given shape and data-type.6. (’x’. optional By default. Numpy provides the recarray class which allows accessing the fields of a record/structured array as attributes. If buf is specified and is an object exposing the buffer interface.5 Record arrays (numpy. An example is [(x. float). e. Record arrays allow the fields to be accessed as members of the array. Normally. int). class numpy. names : tuple of str.g. Array objects . the offset and strides keywords are available.g. Returns rec : recarray Empty array of the given shape and type. formats does not support the new convention of using types directly. optional The desired data-type. using arr.8. Data type objects (dtype). not a tuple.rec) See Also: Creating record arrays (numpy. Given that formats is somewhat limited. Parameters shape : tuple Shape of output array. Arrays may have a data-types containing fields. int). ’f8’. (y. where each entry in the array is a pair of (int. Release 1.y. these attributes are accessed using dictionary lookups such as arr[’x’] and arr[’y’].1 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. ’i4’]. formats : list of data-types. buf : buffer. names. dtype : data-type. float)]. [’i4’.rec). optional The name of each column. recarray record Construct an ndarray that allows field access using attributes. ’y’. optional 188 Chapter 1. ’z’).recarray Construct an ndarray that allows field access using attributes.e. (int. By default. optional A list containing the data-types for the different columns. Other Parameters titles : tuple of str. i. A data-type scalar that allows field access as attribute lookup. the array will use the memory from the existing buffer. e.NumPy Reference. analogous to columns in a spread sheet. Data type routines. 1.x and arr. titles. In this case. we recommend specifying dtype instead. the data-type is determined from formats.

order : {‘C’.x and arr. ’<i4’)]) >>> x[’x’] array([ 1. optional Byte-order for all fields.fromrecords Construct a record array from data. column. using arr. use one of the following methods: 1. 4)]. optional Row-major or column-major order. ‘=’}.view(np. float).NumPy Reference. if names were (’x’. ’y_coordinate’. For example.0. To create a record array from data. 2). strides : tuple of ints. Examples Create an array with two fields..6.x_coordinate. x and y: >>> x = np. ’y’. byteorder : {‘<’. optional Align the fields in memory as the C-compiler would.Create a standard ndarray and convert it to a record array.Use the buf keyword. ’z’) and titles is (’x_coordinate’. 3.0. ’<f8’). Release 1. optional Start reading buffer (buf ) from this offset onwards. 2). (3. occupy in memory). record fundamental data-type for recarray. ’z_coordinate’). Standard array subclasses 189 . dtype=[(’x’.array([(1. ‘F’}. optional Buffer (buf ) is interpreted according to these strides (strides define how many bytes each array element. See Also: rec.recarray) 2. 4)].Use np. Notes This constructor can be compared to empty: it creates a new record array but does not fill it with data. int)]) >>> x array([(1.0. row.]) View the array as a record array: >>> x = x. dtype=[(’x’.view(np. etc.8. names.recarray) 1.rec. titles.1 Aliases for column names. ‘>’. (’y’. (’y’. offset : int. 3. then arr[’x’] is equivalent to both arr. (3.0.fromrecords. format_parser determine a data-type from formats. aligned : bool.

recarray.. 3. dtype=[(’x’. (’z’. Total bytes consumed by the elements of the array. Number of array dimensions.].ndim < 2.y array([2.transpose(). int)]) rec.8. 3. 4. Examples The base of an array that owns its memory is None: 190 Chapter 1. 2..). dtype=[(’x’. Data-type of the array’s elements. float).T Same as self. 24547520). Array objects ..1 >>> x. Python buffer object pointing to the start of the array’s data. 4. An object to simplify the interaction of the array with the ctypes module.ndim < 2..]) >>> x. Tuple of bytes to step in each dimension when traversing an array.2249118382103472e-301....3.]]) >>> x = np.]]) >>> x array([[ 1. 4]) Create a new.]) >>> x.array([(-1073741821. except that self is returned if self.. empty record array: >>> np.. (’z’..T array([ 1. Length of one array element in bytes. 4.. (3471280. Base object if memory is from some other object. A 1-D iterator over the array.x array([ 1.]. .]. Examples >>> x = np.[3.2. [ 3.base Base object if memory is from some other object. Tuple of array dimensions.. ’<i4’)]) Attributes T base ctypes data dtype flags flat imag itemsize nbytes ndim real shape size strides Same as self.array([[1. [ 2.recarray((2. ’<f8’). The imaginary part of the array. 2. 2.4.NumPy Reference. ’<i4’).]) recarray..T array([[ 1.4... Release 1. 1. int). (’y’.]]) >>> x. 3.transpose(). Number of elements in the array. except that self is returned if self. 1..array([1.2.2134086255804012e-316.]) >>> x array([ 1. (’y’.. The real part of the array. Information about the memory layout of the array.. 4. 0)]. 3.

Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes. whose memory is shared with x: >>> y = x[2:] >>> y. This strides information is important for showing how many bytes must be jumped to get to the next element in the array. For example: self. as well as documented private attributes): •data: A pointer to the memory area of the array as a Python integer. Be careful using the ctypes attribute .8. strides.c_double)). This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module. calling self.ndim where the basetype is the same as for the shape attribute. or c_longlong depending on the platform. •shape_as(obj): Return the shape tuple as an array of some other c-types type.6.c_void_p) returns a pointer to memory that 1. The memory area may not even be writeable. Release 1. •shape (c_intp*self. Parameters None Returns c : Python object Possessing attributes data. etc.ctypes An object to simplify the interaction of the array with the ctypes module.strides_as(ctypes.ctypeslib. For example.especially on temporary arrays or arrays constructed on the fly.ctypeslib Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes. •strides (c_intp*self.shape_as(ctypes.3.1 >>> x = np. For example. shape.array([1._as_parameter_ is equivalent to self. Standard array subclasses 191 .4]) >>> x.NumPy Reference. This base-type could be c_int. data.base is None True Slicing creates a view. User Beware! The value of this attribute is exactly the same as self.data_as(ctypes. This memory area may contain data that is not aligned.ndim): A ctypes array of length self. The ctypes array contains the shape of the underlying array.c_void_p).c_short). calling (a+b). 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.ctypes.data_as(ctypes._array_interface_[’data’][0]. •data_as(obj): Return the data pointer cast to a particular c-types object.c_longlong).ndim where the basetype is the C-integer corresponding to dtype(‘p’) on this platform.ndim): A ctypes array of length self. The c_intp type is defined accordingly in numpy.POINTER(ctypes.base is x True recarray. or not in correct byte-order. c_long. The returned object has.2. self. For example: •strides_as(obj): Return the strides tuple as an array of some other c-types type. and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library. This ctypes array contains the strides information from the underlying array. among others. shape. See Also: numpy.

_internal. then the ctypes attribute of array objects still returns something useful.c_longlong)).ctypes.strides <numpy.dtype’> recarray. 1].c_long_Array_2 object at 0x01FCE620> >>> x.data_as(ctypes.ctypes.ctypes.contents c_long(0) >>> x.c_longlong_Array_2 object at 0x01F01300> recarray.POINTER(ctypes. Parameters None Returns d : numpy dtype object See Also: numpy.shape <numpy. Examples >>> import ctypes >>> x array([[0.data_as(ctypes.dtype Data-type of the array’s elements.data 30439712 >>> x. ct will hold a reference to the array until ct is deleted or re-assigned.LP_c_long object at 0x01F01300> >>> x. 3]]) >>> x.core.data_as(ctypes.ctypes. You can avoid this problem using either c=a+b or ct=(a+b).c_longlong) <numpy.dtype) <type ’numpy.core. [2.dtype Examples >>> x array([[0._internal. the object will still have the as parameter attribute which will return an integer equal to the data attribute.c_long_Array_2 object at 0x01FFD580> >>> x. 192 Chapter 1. If the ctypes module is not available._internal.data Python buffer object pointing to the start of the array’s data.ctypes.c_long)).1 is invalid because the array created as (a+b) is deallocated before the next Python statement.ctypes.ctypes.8.dtype dtype(’int32’) >>> type(x._internal.core. In particular.shape_as(ctypes. but ctypes objects are not returned and errors may be raised instead. recarray. Array objects .ctypes. Release 1.c_long_Array_2 object at 0x01FCE620> >>> x.POINTER(ctypes.flags Information about the memory layout of the array. 1]. 3]]) >>> x. In the latter case.POINTER(ctypes.strides_as(ctypes.contents c_longlong(4294967296L) >>> x.ctypes.NumPy Reference.core. [2.c_long) <numpy.c_long)) <ctypes.

currently. so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it. When this array is deallocated. BEHAVED ALIGNED and WRITEABLE. (B) CARRAY BEHAVED and C_CONTIGUOUS. making it read-only. but a (W) view of a writeable array may be subsequently locked while the base array remains writeable. It does not generally hold that self. Standard array subclasses 193 . WRITEABLE.strides[-1] == self. Short flag names are only supported in dictionary access. (C) F_CONTIGUOUS The data is in a single.flags[’WRITEABLE’]). DATA (O) WRITEThe data area can be written to. (F) OWNThe array owns the memory it uses or borrows it from another object. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). locking a base object does not lock any views that already reference it. Only the UPDATEIFCOPY. in that a view of a locked array may not be made writeable. Release 1.flags.itemsize for Fortran-style contiguous arrays is true. Setting this to False locks the data. and ALIGNED flags can be changed by the user. The array flags cannot be set arbitrarily: •UPDATEIFCOPY can only be set False. Arrays can be both C-style and Fortran-style contiguous simultaneously. via direct assignment to the attribute or dictionary entry. (The opposite is not true. but can also be true for higher dimensional arrays.1 Notes The flags object can be accessed dictionary-like (as in a. Fortran-style contiguous segment.8. or by using lowercased attribute names (as in a. the base array DATEIFwill be updated with the contents of this array.) Attempting to change a non-writeable array raises a RuntimeError exception.) inherits WRITEABLE from its base array at creation time. C-style contiguous segment.strides[dim] may be arbitrary if arr. This is clear for 1-dimensional arrays. Even for contiguous arrays a stride for a given dimension arr.setflags. ABLE A view (slice. Attributes C_CONTIGUOUS The data is in a single. •ALIGNED can only be set True if the data is truly aligned.writeable). ALIGNED The data and all elements are aligned appropriately for the hardware. etc.6. However.shape[dim] == 1 or the array has no elements.strides[0] == self. COPY (U) FNC F_CONTIGUOUS and not C_CONTIGUOUS. or by calling ndarray. •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. (A) UPThis array is a copy of some other array.NumPy Reference. (FA) 1. (CA) FARRAY BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.itemsize for C-style contiguous arrays or self.

dtype=np. 6]]) >>> x. 1. which acts similarly to.imag The imaginary part of the array. 3.8.float64) >>> x.reshape(2.imag. Python’s built-in iterator object. flatiter Examples >>> x = np. x array([[3. 3. [4. 5].1 recarray.imag array([ 0. 3]. but is not a subclass of. 5. Examples >>> x = np.flat A 1-D iterator over the array. This is a numpy.flat[3] 4 >>> x.4]] = 1. Release 1.array([1. 3].flat[3] 5 >>> type(x.2.dtype dtype(’float64’) recarray.NumPy Reference. Array objects .complex128) 194 Chapter 1.2. 6]]) >>> x.sqrt([1+0j. 2.itemsize Length of one array element in bytes. 3) >>> x array([[1. [3.flat) <type ’numpy. dtype=np. 0.flat[[1. 3]]) recarray.T. [3.flatiter instance.70710678]) >>> x. Examples >>> x = np. x array([[3. 0+1j]) >>> x.3].arange(1. 4]. See Also: flatten Return a copy of the array collapsed into one dimension.itemsize 8 >>> x = np. 3]]) >>> x.T array([[1. 3]. . 7). [2.flatiter’> An assignment example: >>> x.3]. [3.flat = 3. 1.array([1.

3.real array([ 1.shape) * x.complex128) >>> x. Notes May be used to “reshape” the array. 2. 2. 3]) x. Standard array subclasses 195 .nbytes 480 >>> np.nbytes Total bytes consumed by the elements of the array.5.real equivalent function Examples >>> x = np.) >>> y = np.dtype dtype(’float64’) recarray.ndim Number of array dimensions. 0.shape (4.prod(x. . 3.real The real part of the array.6.2). 4)) 1.ndim y = np.1 >>> x. 3.zeros((2. Notes Does not include memory consumed by non-element attributes of the array object. dtype=np.8. Release 1.70710678]) >>> x.itemsize 16 recarray.itemsize 480 recarray. Examples >>> >>> 1 >>> >>> 3 x = np. 4)) y. Examples >>> x = np.zeros((2. 4]) >>> x.NumPy Reference.real.sqrt([1+0j. See Also: numpy.array([1. 0+1j]) >>> x.shape Tuple of array dimensions.zeros((3. as long as this would not require a change in the total number of elements Examples >>> x = np.ndim recarray.array([1.

[16.. 0.size 30 >>> np. 8. Release 1. 3].. 1. but 20 bytes (5 values) to get to the same position in the next row.lib. 13. Examples >>> y = np. 4).... 6) Traceback (most recent call last): File "<stdin>". dtype=np. 19]. 3. in <module> ValueError: total size of new array must be 0.prod(a. 10. [ 0. 4) >>> y. 2).arange(2*3*4). 15]. 0.strides) A more detailed explanation of strides can be found in the “ndarray.3.. 7. Examples >>> x = np.. 4]. 0.shape = (3. Array objects .zeros((3. 14.. 8) >>> y array([[ 0.shape (2..complex128) >>> x. 6. For example... 2. 5.. the product of the array’s dimensions. 0.array([[0.].array(i) * a. 21.prod(x. 3. (2. 0. 0. . i[1].e. 0. 0.]]) unchanged recarray..as_strided Notes Imagine an array of 32-bit integers (each 4 bytes): x = np. one after the other (known as a contiguous block of memory). 0. line 1.reshape(np.. 0.. 0. 11]]..shape). The byte offset of element (i[0].shape) 30 recarray. 0.stride_tricks. 9]]. 9. [[12. [20. [ 0.]. 0.size Number of elements in the array...NumPy Reference.strides Tuple of bytes to step in each dimension when traversing an array. dtype=np. 18.. 5. [5. 23]]]) 196 Chapter 1. 0. See Also: numpy. 22. 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.rst” file in the NumPy reference guide. [ 4. 1. 7]. 0.. 0. i... 17. As such. 0. the strides for the array x will be (20. 2. we have to skip 4 bytes (1 value) to move to the next column. >>> y. [ 8.1 >>> y..int32) This array is stored in memory as 40 bytes. 0. 0.shape = (3.. 0. 6.8.. i[n]) in an array a is: offset = sum(np.4)) >>> y array([[[ 0. Equivalent to np.

1.3. Return a copy of the array collapsed into one dimension.2.strides * np. (5.arange(5*6*7*8). Copy an element of an array to a standard Python scalar and return it.6. Swap the bytes of the array elements Use an index array to construct a new array from a set of choices. axis2]) dot(b[. Release 1. Return selected slices of this array along given axis.NumPy Reference. out]) dump(file) dumps() field(attr[. axis. Return the indices of the elements that are non-zero.strides (32. out]) min([axis. Fill the array with a scalar value. Complex-conjugate all elements.2.0) >>> x. Dump a pickle of the array to the specified file. out]) argmin([axis. order]) astype(dtype[. a_max]. axis. Return specified diagonals. 224. kind. Returns True if any of the elements of a evaluate to True. Return indices of the minimum values along the given axis of a. Return the complex conjugate.8)). 4) >>> y[1. out]) conj() conjugate() copy([order]) cumprod([axis. out]) compress(condition[. out]) argpartition(kth[. Returns the average of the array elements along given axis. axis. subok.strides (48. 16. Insert scalar into an array (scalar is cast to array’s dtype. order.array([3. dtype. dtype.1))) >>> offset/y. Rearranges the elements in the array in such a way that value of the element in kth po Return the product of the array elements over the given axis 197 . out]) cumsum([axis. element-wise.7. axis1. copy]) byteswap(inplace) choose(choices[. Return the cumulative product of the elements along the given axis. order]) argsort([axis. kind.itemsize 17 >>> x = np. out]) argmax([axis. Return an array whose values are limited to [a_min.array((1.2]) >>> offset = sum(i * x. dtype. if possible) Return the maximum along a given axis.2] 813 >>> offset / x.1 >>> y. Standard array subclasses Returns True if all elements evaluate to True. out.8. 1344) >>> i = np.reshape(np. Return the cumulative sum of the elements along the given axis. casting. order]) prod([axis. Return indices of the maximum values along the given axis. out]) diagonal([offset.1] 17 >>> offset=sum(y.strides) >>> x[3.itemsize 813 Methods all([axis. Returns the indices that would sort this array. Return the array with the same data viewed with a different byte order. Returns the indices that would partition this array. a_max[. out]) newbyteorder([new_order]) nonzero() partition(kth[. 4. out]) 1. dtype. kind. offset]) item(*args) itemset(*args) max([axis. cast to a specified type. out]) any([axis. Dot product of two arrays. val]) fill(value) flatten([order]) getfield(dtype[.transpose(2. Returns a field of the given array as a certain type.6.5. Return the minimum along a given axis.1. Returns the pickle of the array as a string. out]) mean([axis. Return a copy of the array. mode]) clip(a_min.5. Copy of the array.1.

Put a value into a specified place in a field defined by a data-type.flat[n] = values[n] for all n in indices. Refer to numpy. dtype. See Also: numpy. out. out.any for full documentation. Return the array as a (possibly nested) list.argmax(axis=None. Returns the variance of the array elements. axis2) take(indices[. dtype. out=None) Returns True if any of the elements of a evaluate to True.all for full documentation.any(axis=None.1 ptp([axis. along given axis. sorter]) setfield(val. Returns the standard deviation of the array elements along given axis. axis. Construct a Python string containing the raw data bytes in the array. align. Release 1. out]) transpose(*axes) var([axis.any equivalent function recarray. ALIGNED.argmax for full documentation. Returns an array containing the same data with a new shape. Return an array formed from the elements of a at the given indices. ddof]) view([dtype. Repeat elements of an array. ddof]) sum([axis. refcheck]) round([decimals. Returns a view of the array with axes transposed. Remove single-dimensional entries from the shape of a. axis2. Return a with each element rounded to the given number of decimals. dtype. side.48 – continued from previous page Peak to peak (maximum .minimum) value along a given axis. out]) put(indices. out=None) Return indices of the maximum values along the given axis. Return a flattened array. out. axis1.all(axis=None. uic]) sort([axis. mode]) tofile(fid[.NumPy Reference. order]) squeeze([axis]) std([axis. respectively. Set array flags WRITEABLE. recarray. format]) tolist() tostring([order]) trace([offset. out]) searchsorted(v[. See Also: numpy. type]) Table 1. and UPDATEIFCOPY.8. Find indices where elements of v should be inserted in a to maintain order. mode]) ravel([order]) repeat(repeats[. Refer to numpy. sep.argmax equivalent function 198 Chapter 1. See Also: numpy. Return the sum along diagonals of the array. dtype. out=None) Returns True if all elements evaluate to True. Write array to a file as text or binary (default). in-place. Change shape and size of array in-place. out]) swapaxes(axis1. axis]) reshape(shape[. Refer to numpy. order]) resize(new_shape[. kind. Sort an array.all equivalent function recarray. Return the sum of the array elements over the given axis. Return a view of the array with axis1 and axis2 interchanged. offset]) setflags([write. Array objects . Set a. dtype[. values[.

Standard array subclasses 199 . ‘C’ order otherwise. out=None) Return indices of the minimum values along the given axis of a. • ‘same_kind’ means only safe casts or casts within a kind. • ‘unsafe’ means any data conversions may be done. • ‘no’ means the data types should not be cast at all.argpartition equivalent function recarray. order=’K’. ‘A’. ‘F’. Refer to numpy. copy=True) Copy of the array. optional 1. • ‘equiv’ means only byte-order changes are allowed.6. Default is ‘K’. optional Controls the memory layout order of the result. ‘A’ means ‘F’ order if all the arrays are Fortran contiguous. casting : {‘no’. ‘C’ means C order. Parameters dtype : str or dtype Typecode or data-type to which the array is cast. subok=True.NumPy Reference. See Also: numpy. kind=’quicksort’. cast to a specified type. optional Controls what kind of data casting may occur. Defaults to ‘unsafe’ for backwards compatibility.argmin for detailed documentation. subok : bool. like float64 to float32. New in version 1. ‘unsafe’}.argsort for full documentation. ‘same_kind’.argsort(axis=-1. and ‘K’ means as close to the order the array elements appear in memory as possible.1 recarray.8. order : {‘C’.argpartition for full documentation.argmin equivalent function recarray.8. axis=-1. order=None) Returns the indices that would partition this array. order=None) Returns the indices that would sort this array.argpartition(kth.astype(dtype.0. See Also: numpy. See Also: numpy. casting=’unsafe’. Release 1. ‘F’ means Fortran order. are allowed. Refer to numpy. • ‘safe’ means only casts which can preserve values are allowed. kind=’introselect’. ‘equiv’. ‘K’}. ‘safe’. Refer to numpy.argsort equivalent function recarray.argmin(axis=None.

byteswap(inplace) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array. Parameters inplace : bool. this is a view to self. Array objects . 2. To avoid this. If this is set to false. Release 1. arr_t is a new array of the same shape as the input array. 1. and the dtype. optionally swapped in-place. 2. 2.NumPy Reference. copy : bool.5]) >>> x. order. If inplace is True. otherwise the returned array will be forced to be a base-class array. Raises ComplexWarning When casting from complex to float or int. ’fac’]) >>> A. then sub-classes will be passed-through (default).astype(t). and subok requirements are satisfied. 256.array([’ceg’. dtype=int16) >>> map(hex. Examples >>> A = np. 2. dtype=np.astype(int) array([1. ’0x100’. 2. 13090]. with dtype.byteswap() 200 Chapter 1. . 2]) recarray. Returns out : ndarray The byteswapped array. the input array is returned instead of a copy.real. astype always returns a newly allocated array. 8755].8. a. swap bytes in-place. order given by dtype.1 If True. default is False. A) [’0x1’.5]) >>> x array([ 1.byteswap(True) array([ 256. optional If True. ’0x2233’] >>> A. one should use Examples >>> x = np.array([1. ’0x1’. ’0x3322’] Arrays of strings are not swapped >>> A = np. order. optional By default.array([1. .int16) >>> map(hex. Returns arr_t : ndarray Unless copy is False and the other conditions for returning the input array are satisfied (see description for copy input paramter). A) [’0x100’.

See Also: numpy. ‘K’}.choose equivalent function recarray. See Also: numpy. See Also: numpy.NumPy Reference. Release 1.conj() Complex-conjugate all elements. axis=None. out=None) Return selected slices of this array along given axis. Refer to numpy.choose for full documentation. Standard array subclasses 201 .conjugate for full documentation. Refer to numpy. Refer to numpy.conjugate() Return the complex conjugate. element-wise. See Also: numpy. See Also: numpy. ’fac’]. a_max.choose(choices.compress(condition. mode=’raise’) Use an index array to construct a new array from a set of choices.8. ‘F’.1 array([’ceg’.6. optional 1. dtype=’|S3’) recarray.conjugate equivalent function recarray. Refer to numpy. Refer to numpy.conjugate for full documentation. Parameters order : {‘C’.compress equivalent function recarray.conjugate equivalent function recarray. out=None.clip equivalent function recarray.copy(order=’C’) Return a copy of the array.clip(a_min. ‘A’. out=None) Return an array whose values are limited to [a_min.clip for full documentation.compress for full documentation. a_max].

out=None) Return the cumulative product of the elements along the given axis. (Note that this function and :func:numpy. See Also: numpy. [0.cumsum for full documentation.diagonal equivalent function 202 Chapter 1. order=’F’) >>> y = x.) See Also: numpy. Refer to numpy. 0]. ‘C’ means C-order.8. 3].NumPy Reference. See Also: numpy. ‘C’ otherwise.cumprod equivalent function recarray. numpy. 6]]) >>> y.copy() >>> x.copy are very similar.copyto Examples >>> x = np. out=None) Return the cumulative sum of the elements along the given axis. Release 1. Refer to numpy.cumprod for full documentation. [4.6]].fill(0) >>> x array([[0. See Also: numpy.diagonal for full documentation.1 Controls the memory layout of the copy.array([[1.5. axis1=0.diagonal(offset=0. ‘K’ means match the layout of a as closely as possible. 0. ‘F’ means F-order. axis2=1) Return specified diagonals. ‘A’ means ‘F’ if a is Fortran contiguous. but have different default values for their order= arguments.[4.cumsum equivalent function recarray.cumsum(axis=None. 0. Refer to numpy. 0]]) >>> y array([[1.copy. dtype=None.2.cumprod(axis=None.3].flags[’C_CONTIGUOUS’] True recarray. dtype=None. Array objects . 2. 5.

[ 8.ones((2. recarray.empty(2) >>> a.1 recarray. 8.. See Also: numpy.6. val=None) recarray. [ 2. 0]) >>> a = np. 8. out=None) Dot product of two arrays.NumPy Reference. 2.dot equivalent function Examples >>> a = np.]]) recarray...].dot(b.dot(b) array([[ 2. The array can be read back with pickle. Parameters None recarray.].dot for full documentation.fill(1) >>> a array([ 1. Parameters file : str A string naming the dump file.dot(b) array([[ 8. 2)) * 2 >>> a.fill(0) >>> a array([0. 1.loads or numpy.loads will convert the string back to an array.eye(2) >>> b = np.dumps() Returns the pickle of the array as a string. Refer to numpy. 2]) >>> a.dot(b)..load. pickle.dump(file) Dump a pickle of the array to the specified file. Release 1.load or numpy. Parameters value : scalar All elements of a will be assigned this value.fill(value) Fill the array with a scalar value.8..array([1.]) 1.]]) This array method can be conveniently chained: >>> a. Examples >>> a = np. Standard array subclasses 203 .field(attr. 2.

flat A 1-D flat iterator over the array.]]) By choosing an offset of 8 bytes we can select the complex part of the array for our view: 204 Chapter 1. Parameters order : {‘C’.array([[1.8. 0.diag([1. offset=0) Returns a field of the given array as a certain type.+4. ‘A’}.4]]) >>> a. flattened to one dimension.+0.j]]) >>> x. 3. ‘F’.. The dtype size of the view can not be larger than that of the array itself.2].flatten(order=’C’) Return a copy of the array collapsed into one dimension. 3. Release 1. If taking a view with a 32-bit integer (4 bytes). The values in the view are determined by the given type and the offset into the current array in bytes. Examples >>> a = np.float64) array([[ 1. offset : int Number of bytes to skip before beginning the element view. See Also: ravel Return a flattened array. 1] = 2 + 4.j >>> x array([[ 1. optional Whether to flatten in C (row-major).+1. 0. the offset needs to be between 0 and 12 bytes. 2.j]. 4]) >>> a. [ 0.+1. Parameters dtype : str or dtype The data type of the view. or preserve the C/Fortran ordering from a.. 4]) recarray.1 recarray.j. The offset needs to be such that the view dtype fits in the array dtype.+0. [3.flatten(’F’) array([1.j]*2) >>> x[1. A field is a view of the array data with a given data-type. Returns y : ndarray A copy of the input array. for example an array of dtype complex128 has 16-byte elements.j. 2. 2.getfield(dtype. Examples >>> x = np. Array objects . [ 0.flatten() array([1.]. Fortran (column-major) order.getfield(np. The default is ‘C’.NumPy Reference. 2.

the method only works for arrays with one element (a. which element is copied into a standard Python scalar object and returned. Release 1.].size == 1).itemset(*args) Insert scalar into an array (scalar is cast to array’s dtype.item(*args) Copy an element of an array to a standard Python scalar and return it. 5. 3]]) >>> x. Parameters *args : Arguments (variable number and type) • none: in this case. 3]. size=(3. item() returns a scalar array object because there is no available Python scalar that would not lose information.1 >>> x.6.item((0. if possible) There must be at least 1 argument.getfield(np. 2)) 3 recarray. • int_type: this argument is interpreted as a flat index into the array. 0. instead of an array scalar. 7]. offset=8) array([[ 1. a standard Python scalar is returned. in which case a tuple is returned. • tuple of int_types: functions as does a single int_type argument.8. Standard array subclasses 205 . a.item((2. [2.random. 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.NumPy Reference. item is very similar to a[args]. and define the last argument as item. 4. unless fields are defined. specifying which element to copy and return. except. Then.randint(9. Examples >>> x = np.item(3) 2 >>> x.float64..itemset(*args) is equivalent to but faster than a[args] = item.. except that the argument is interpreted as an nd-index into the array. 8. 1)) 1 >>> x. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math.]]) recarray. [8. Void arrays return a buffer object for item().item(7) 5 >>> x. Parameters *args : Arguments 1. [ 0. The item should be a scalar value and args must select a single item in the array a. 3)) >>> x array([[3. 1.

5.mean equivalent function recarray. 7]. 2). Also. when using itemset (and item) inside a loop.amax for full documentation. Refer to numpy. out=None) Returns the average of the array elements along given axis. itemset provides some speed increase for placing a scalar into a particular location in an ndarray.newbyteorder(new_order=’S’) Return the array with the same data viewed with a different byte order.mean(axis=None. [8. If two arguments: the last argument is the value to be set and must be a scalar. 3)) >>> x array([[3. It is either an int or a tuple.1 If one argument: a scalar. 7]. 5. [2.NumPy Reference.8. 3]]) >>> x. if you must do this.randint(9. out=None) Return the minimum along a given axis. 8. 3].amin for full documentation. out=None) Return the maximum along a given axis. 3]. Examples >>> x = np. See Also: numpy.min(axis=None. be sure to assign the methods to a local variable to avoid the attribute look-up at each loop iteration.amax equivalent function recarray. Refer to numpy. However. 9]]) recarray.itemset(4. 1.max(axis=None. 0) >>> x. 0. Equivalent to: 206 Chapter 1. See Also: numpy. Release 1. 9) >>> x array([[3. it complicates the appearance of the code. See Also: numpy. [8. only used in case a is of size 1.itemset((2.amin equivalent function recarray.mean for full documentation. the first argument specifies a single array element location. [2. size=(3. Array objects . 1. dtype=None. Refer to numpy. generally this is discouraged: among other problems.random. Notes Compared to indexing syntax.

optional Byte order to force. Parameters kth : int or sequence of ints Element index to partition by.nonzero for full documentation. a value from the byte order specifications above. New in version 1.little endian .nonzero() Return the indices of the elements that are non-zero. The ordering of the elements in the two partitions is undefined. recarray. Standard array subclasses 207 . The code does a case-insensitive check on the first letter of new_order for the alternatives above.ignore (no change to byte order) The default value (‘S’) results in swapping the current byte order.6.newbytorder(new_order)) Changes are also made in all fields and sub-arrays of the array data type. The kth element value will be in its final sorted position and all smaller elements will be moved before it and all equal or greater elements behind it. For example. Returns new_arr : array New array object with the dtype reflecting given change to the byte order.8. which means sort along the last axis. {’|’. order : list. Release 1. Refer to numpy. Not all fields need be specified.8.nonzero equivalent function recarray.partition(kth.view(arr. {’=’.NumPy Reference. All elements smaller than the kth element are moved before this element and all equal or greater are moved behind it. The order all elements in the partitions is undefined. axis=-1. Parameters new_order : string. If provided with a sequence of kth it will partition all elements indexed by kth of them into their sorted position at once. Default is ‘introselect’. See Also: numpy. 1.native order . optional When a is an array with fields defined. etc.1 arr. order=None) Rearranges the elements in the array in such a way that value of the element in kth position is in the position it would be in a sorted array. optional Selection algorithm. Default is -1. second. new_order codes can be any of: * * * * * ’S’ {’<’. any of ‘B’ or ‘b’ or ‘biggish’ are valid to specify big-endian.dtype. kind=’introselect’. swap ’L’} ’B’} ’N’} ’I’} dtype from current to opposite endian . this argument specifies which fields to compare first. {’>’.big endian . kind : {‘introselect’}. axis : int. optional Axis along which to sort.0.

See Also: numpy. sort Full sort. out=None) Peak to peak (maximum .partition Return a parititioned copy of an array.1 See Also: numpy. Release 1.flat[n] = values[n] for all n in indices.partition for notes on the different algorithms. Refer to numpy. values. 3.prod for full documentation. 3) >>> a array([2. argpartition Indirect partition.ravel for full documentation.ptp for full documentation. See Also: numpy.prod equivalent function recarray.ravel([order ]) Return a flattened array. Examples >>> a = np. Array objects .put for full documentation. Notes See np. 3. 3)) array([1.ptp equivalent function recarray. 4]) >>> a.partition(a. 2. mode=’raise’) Set a.partition((1. 2. See Also: numpy. 4]) recarray.prod(axis=None. dtype=None. out=None) Return the product of the array elements over the given axis Refer to numpy. 1]) >>> a. 1.minimum) value along a given axis.8. Refer to numpy. Refer to numpy.array([3. 4.NumPy Reference.ptp(axis=None.put(indices. See Also: 208 Chapter 1.put equivalent function recarray.

reshape equivalent function recarray. optional If False. reference count will not be checked. or n ints Shape of resized array. Returns None Raises ValueError If a does not own its own data or references or views to it exist. Parameters new_shape : tuple of ints. axis=None) Repeat elements of an array.resize(new_shape. 1.repeat(repeats. order=’C’) Returns an array containing the same data with a new shape. Refer to numpy. Refer to numpy.8. See Also: numpy.reshape(shape.ravel equivalent function ndarray. Standard array subclasses 209 . recarray.repeat for full documentation. Default is True. See Also: resize Return a new array with the specified shape. Only contiguous arrays (data elements consecutive in memory) can be resized.6.1 numpy.flat a flat iterator on the array.repeat equivalent function recarray.reshape for full documentation. Release 1.NumPy Reference. Notes This reallocates space for the data area if necessary. refcheck : bool. SystemError If the order keyword argument is specified. and the data memory must be changed. refcheck=True) Change shape and size of array in-place. See Also: numpy. This behaviour is a bug in NumPy.

1]. 1)) >>> a array([[0]. and reshaped: >>> a = np. then you may safely set refcheck to False. Release 1. 1]. [2]]) Enlarging an array: as above. Refer to numpy.NumPy Reference.8..array([[0. order=’F’) >>> a. [3. 3]]) >>> b. out=None) Return a with each element rounded to the given number of decimals. [2. For full documentation.round(decimals=0. 1)) Traceback (most recent call last): . [2. 3]].. 1). see numpy. [2. 3) # new_shape parameter doesn’t have to be a tuple >>> b array([[0.resize((2.resize((1.searchsorted 210 Chapter 1.resize(2.around for full documentation.. but missing entries are filled with zeros: >>> b = np.. 1)) >>> a array([[0].array([[0. >>> c = a >>> a.array([[0.around equivalent function recarray. 1.. See Also: numpy.resize((2. 1]. 2]. sorter=None) Find indices where elements of v should be inserted in a to maintain order. side=’left’.resize((1. Examples Shrinking an array: array is flattened (in the order that the data are stored in memory). [1]]) >>> a = np. However. 0. 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.. resized. refcheck=False) >>> a array([[0]]) >>> c array([[0]]) recarray. Unless refcheck is False: >>> a. ValueError: cannot resize an array that has been referenced . order=’C’) >>> a.searchsorted(v. 3]]. 0]]) Referencing an array prevents resizing. Array objects .1 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.

3.. 1. [3.00000000e+000]]) recarray.]]) 1. (The exception for string is made so that unpickling can be done without copying memory. Returns None See Also: getfield Examples >>> x = np.8.eye(3) >>> x.. ALIGNED. 3.. and UPDATEIFCOPY.getfield(np.]. offset : int.]]) >>> x.) 1.searchsorted equivalent function recarray. or is a string. [ 0.48219694e-323]. The ALIGNED flag can only be set to True if the data is actually aligned according to the type. Standard array subclasses 211 . The UPDATEIFCOPY flag can never be set to True. [ 0. Release 1.48219694e-323.. 1.int32) array([[3.48219694e-323].. Place val into a‘s field defined by dtype and beginning offset bytes into the field. 0.6.setfield(val. dtype.float64) array([[ 1. 1. or the ultimate owner of the memory exposes a writeable buffer interface. 1. 3]]) >>> x array([[ 1. Parameters val : object Value to be placed in field. 1. 3].setfield(3. np.00000000e+000.48219694e-323. 1.. 1.NumPy Reference. 0. [ 1.eye(3). optional The number of bytes into the field at which to place val. 0. align=None..int32) >>> x array([[ 1.. 0. 0. [ 0. 0. uic=None) Set array flags WRITEABLE. respectively..getfield(np. dtype : dtype object Data-type of the field in which to place val..setflags(write=None. np.int32) >>> x.setfield(np.00000000e+000. [ 0.]. The flag WRITEABLE can only be set to True if the array owns its own memory... 1. offset=0) Put a value into a specified place in a field defined by a data-type. 3. 1. [3. 0.48219694e-323.]. [ 1. 0.1 See Also: numpy.48219694e-323. >>> x. These Boolean-valued flags affect how numpy interprets the memory area used by a (see Notes below). 3].].

WRITEABLE (W) the data area can be written to. which means sort along the last axis.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y. uic : bool. Notes Array flags provide information about how the memory area used for the array is to be interpreted. kind=’quicksort’.1 Parameters write : bool. 0. 9]]) >>> y. WRITEABLE. in-place. 0]. the base array will be updated with the contents of this array. UPDATEIFCOPY (U) this array is a copy of some other array (referenced by .8. in <module> ValueError: cannot set UPDATEIFCOPY flag to True recarray. align=0) >>> y. Release 1. [8. optional Describes whether or not a is aligned properly for its type. optional Describes whether or not a is a copy of another “base” array. Array objects .base). 7]. 1. optional Axis along which to sort. 212 Chapter 1.setflags(write=0. Parameters axis : int. ALIGNED (A) the data and strides are aligned appropriately for the hardware (as determined by the compiler).flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : True WRITEABLE : False ALIGNED : False UPDATEIFCOPY : False >>> y. There are 6 Boolean flags in use. Default is -1.sort(axis=-1. optional Describes whether or not a can be written to.NumPy Reference. order=None) Sort an array. line 1. All flags can be accessed using their first (upper case) letter as well as the full name. and ALIGNED. When this array is deallocated. align : bool. only three of which can be changed by the user: UPDATEIFCOPY.setflags(uic=1) Traceback (most recent call last): File "<stdin>". [2. 5. Examples >>> y array([[3.

NumPy Reference. ’<i4’)]) recarray. ’|S1’). [1. Refer to numpy. 3]]) >>> a.1 kind : {‘quicksort’.array([(’a’.squeeze for full documentation. Examples >>> a = np.squeeze equivalent function 1. ‘heapsort’}. 3].squeeze(axis=None) Remove single-dimensional entries from the shape of a. optional Sorting algorithm. dtype=[(’x’. etc. lexsort Indirect stable sort on multiple keys. Default is ‘quicksort’. 1)]. (’y’. (’y’. See Also: numpy. second.6. Not all fields need be specified.sort(axis=0) >>> a array([[1. Standard array subclasses 213 . dtype=[(’x’. [3. 1). [1. int)]) >>> a.sort Return a sorted copy of an array.8.array([[1.sort(axis=1) >>> a array([[1.1]]) >>> a. optional When a is an array with fields defined. ‘mergesort’. order : list. partition Partial sort. searchsorted Find elements in sorted array. 2).4]. 2)].sort(order=’y’) >>> a array([(’c’. this argument specifies which fields to compare first. 4]. (’c’. 4]]) Use the order keyword to specify a field to use when sorting a structured array: >>> a = np. Notes See sort for notes on the different sorting algorithms. See Also: numpy. Release 1. ’S1’). argsort Indirect sort. (’a’.

The data produced by this method can be recovered using the function fromfile(). or a string containing a filename. 214 Chapter 1.swapaxes equivalent function recarray.swapaxes(axis1. Each entry in the array is formatted to text by first converting it to the closest Python type. See Also: numpy.take equivalent function recarray. and then using “format” % item. independent of the order of a. mode=’raise’) Return an array formed from the elements of a at the given indices. sep : str Separator between array items for text output. Refer to numpy.std(axis=None.8. Refer to numpy. Parameters fid : file or str An open file object. axis2) Return a view of the array with axis1 and axis2 interchanged. If “” (empty).NumPy Reference.sum for full documentation.write(a. equivalent to file.std equivalent function recarray. out=None) Return the sum of the array elements over the given axis. ddof=0) Returns the standard deviation of the array elements along given axis. See Also: numpy.sum equivalent function recarray. Refer to numpy.sum(axis=None. See Also: numpy.1 recarray. axis=None. Release 1. See Also: numpy.take(indices. a binary file is written. out=None.tofile(fid. out=None. dtype=None. Array objects .take for full documentation.tostring()). format : str Format string for text file output. Data is always written in ‘C’ order.std for full documentation. Refer to numpy. sep=”“. format=”%s”) Write array to a file as text or binary (default). dtype=None.swapaxes for full documentation.

1]. 2]). [3. Standard array subclasses 215 . Information on endianness and precision is lost. array([3. Data items are converted to the nearest compatible Python type. 4]]) >>> list(a) [array([1. optional Order of the data for multidimensional arrays: C.tolist() Return the array as a (possibly nested) list. in which case it means ‘Fortran’ order. a = np.tostring(’C’) == x. Returns s : str A Python string exhibiting a copy of a‘s raw data. Fortran. The string can be produced in either ‘C’ or ‘Fortran’. Examples >>> a = np. 2]) >>> a. or ‘Any’ order (the default is ‘C’-order). Release 1.1 Notes This is a convenience function for quick storage of array data. ‘F’. [2.tolist()). 2] >>> a = np.NumPy Reference. or the same as for the original array. Constructs a Python string showing a copy of the raw contents of data memory. ‘Any’ order means C-order unless the F_CONTIGUOUS flag in the array is set. recarray. 4])] >>> a.array([[1.array([1.array(a. 3]]) >>> x. None}. 2]. so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. 2]. [3. Examples >>> x = np.tolist() [1. Some of these problems can be overcome by outputting the data as text files.tolist() [[1. at the expense of speed and file size.6.tostring() ’\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00’ >>> x. Return a copy of the array data as a (nested) Python list.tostring(order=’C’) Construct a Python string containing the raw data bytes in the array. 4]] recarray. Parameters order : {‘C’.tostring() True 1.8.array([[0. Parameters none Returns y : list The possibly nested list of array elements. Notes The array may be recreated.

Refer to numpy. this is the usual matrix transpose. then a. [2. Parameters axes : None. i[n-1]).T Array property returning the array transposed. • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a. axis1=0.trace for full documentation. with axes suitably permuted.shape = (i[n-1].transpose()‘s j-th axis. 3]. If axes are not provided and a. For an n-D array. 4]]) 216 Chapter 1. (To change between column and row vectors. i[n-2]. 3]. See Also: ndarray. 4]]) >>> a array([[1. this has no effect. if axes are given. .transpose() array([[1.. i[1]. [3.transpose(*axes) Returns a view of the array with axes transposed.tostring(’F’) ’\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00’ recarray. i[0]).shape = (i[0]. 3].array([[1.trace equivalent function recarray.trace(offset=0. 2]. first cast the 1-D array into a matrix object. [2.) For a 2-D array. • 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.. Examples >>> a = np. i[1]. dtype=None. [2. For a 1-D array. 0) array([[1.transpose((1. i[n-2]. Array objects .NumPy Reference. or n ints • None or no argument: reverses the order of the axes. out=None) Return the sum along diagonals of the array..8. 4]]) >>> a. 4]]) >>> a. 2]. . axis2=1. 4]]) >>> a.1 >>> x..transpose(). [3.transpose(1. their order indicates how the axes are permuted (see Examples). See Also: numpy. Release 1. tuple of ints. 0)) array([[1.

var equivalent function recarray. type=None) class numpy.6.data pointer to start of data record.flat a 1-d view of scalar record.NumPy Reference.T transpose record.flags integer value of flags record.1 recarray. Refer to numpy.record A data-type scalar that allows field access as attribute lookup.itemsize length of one element in bytes 1. Attributes T base data dtype flags flat imag itemsize nbytes ndim real shape size strides transpose base object pointer to start of data dtype object integer value of flags a 1-d view of scalar imaginary part of scalar length of one element in bytes length of item in bytes number of array dimensions real part of scalar tuple of array dimensions number of elements in the gentype tuple of bytes steps in each dimension record.view(dtype=None. out=None.imag imaginary part of scalar record.base base object record. Standard array subclasses 217 .var for full documentation.dtype dtype object record. dtype=None. along given axis.8. ddof=0) Returns the variance of the array elements.var(axis=None. See Also: numpy. Release 1.

nbytes length of item in bytes record.ndim number of array dimensions record. Not implemented (virtual attribute) Pretty-print all fields. Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Continued on next page Chapter 1.1 record.strides tuple of bytes steps in each dimension Methods all any argmax argmin argsort astype byteswap choose clip compress conj conjugate copy cumprod cumsum diagonal dump dumps fill flatten getfield item itemset max mean min newbyteorder([new_order]) nonzero pprint() prod ptp put ravel repeat 218 Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Return a new dtype with a different byte order. Release 1.8.size number of elements in the gentype record.NumPy Reference. Array objects .real real part of scalar record.shape tuple of array dimensions record.

albeit unimplemented.50 – continued from previous page Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) Not implemented (virtual attribute) record. See Also: The record. all the attributes of the ndarray class so as to provide a uniform API.argmin() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. all the attributes of the ndarray class so as to provide a uniform API.all() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. Standard array subclasses 219 . See Also: The record.NumPy Reference.8. See Also: The 1. albeit unimplemented.any() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. Release 1. and possesses. albeit unimplemented.1 reshape resize round searchsorted setfield setflags sort squeeze std sum swapaxes take tofile tolist tostring trace transpose var view Table 1. albeit unimplemented.argmax() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses.6.

and possesses. albeit unimplemented.clip() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. albeit unimplemented. albeit unimplemented. and possesses. Release 1. all the attributes of the ndarray class so as to provide a uniform API.argsort() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. See Also: The record. and possesses. See Also: The record.1 record. Array objects .conjugate() Not implemented (virtual attribute) 220 Chapter 1. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. See Also: The record. See Also: The record. all the attributes of the ndarray class so as to provide a uniform API.conj() record. and possesses.astype() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.NumPy Reference.choose() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.compress() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.8.byteswap() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented.

See Also: The record. Standard array subclasses 221 . See Also: The record.diagonal() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API.NumPy Reference. and possesses.cumsum() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. and possesses.dump() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The 1. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. See Also: The record.1 Class generic exists solely to derive numpy scalars from. and possesses. Release 1. all the attributes of the ndarray class so as to provide a uniform API. See Also: The record.cumprod() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.6.dumps() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. and possesses.8. albeit unimplemented. albeit unimplemented. and possesses. albeit unimplemented. and possesses. See Also: The record. all the attributes of the ndarray class so as to provide a uniform API.copy() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented.

See Also: The record. all the attributes of the ndarray class so as to provide a uniform API.mean() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. and possesses. Release 1.item() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented.8. See Also: The record. and possesses. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented. See Also: The record. all the attributes of the ndarray class so as to provide a uniform API.NumPy Reference.flatten() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.min() Not implemented (virtual attribute) 222 Chapter 1. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API.fill() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses.itemset() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. Array objects .getfield() record. all the attributes of the ndarray class so as to provide a uniform API. See Also: The record. albeit unimplemented. albeit unimplemented. and possesses.1 record. albeit unimplemented. and possesses. See Also: The record.max() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.

albeit unimplemented. optional Byte order to force.ptp() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. any of ‘B’ or ‘b’ or ‘biggish’ are valid to specify big-endian. See Also: The record. See Also: The record.NumPy Reference.native order •‘S’ . The new_order code can be any from the following: •{‘<’. The code does a case-insensitive check on the first letter of new_order for the alternatives above.6. and possesses.swap dtype from current to opposite endian •{‘|’.newbyteorder(new_order=’S’) Return a new dtype with a different byte order. ‘N’} . ‘I’} . all the attributes of the ndarray class so as to provide a uniform API. and possesses. record.prod() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.8. Release 1. albeit unimplemented.little endian •{‘>’. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented.nonzero() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. For example. Standard array subclasses 223 . albeit unimplemented. a value from the byte order specifications above.ignore (no change to byte order) Parameters new_order : str. 1. Changes are also made in all fields and sub-arrays of the data type. ‘B’} . and possesses.pprint() Pretty-print all fields. The default value (‘S’) results in swapping the current byte order. all the attributes of the ndarray class so as to provide a uniform API. record. and possesses. ‘L’} . Returns new_dtype : dtype New dtype object with the given change to the byte order. all the attributes of the ndarray class so as to provide a uniform API.1 Class generic exists solely to derive numpy scalars from.big endian •{‘=’.

albeit unimplemented. and possesses. all the attributes of the ndarray class so as to provide a uniform API. Array objects . See Also: The record.repeat() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record.ravel() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. and possesses. Release 1. albeit unimplemented. See Also: The record. See Also: The record.searchsorted() Not implemented (virtual attribute) 224 Chapter 1. albeit unimplemented. and possesses.1 See Also: The record.reshape() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.resize() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. albeit unimplemented.put() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.round() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.8. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. all the attributes of the ndarray class so as to provide a uniform API. and possesses. See Also: The record.NumPy Reference. all the attributes of the ndarray class so as to provide a uniform API. and possesses. albeit unimplemented.

albeit unimplemented. See Also: The record. and possesses. See Also: The record. Release 1. all the attributes of the ndarray class so as to provide a uniform API. and possesses.std() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. Standard array subclasses 225 .setfield() record. all the attributes of the ndarray class so as to provide a uniform API.sum() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.NumPy Reference. and possesses.8. See Also: The record.squeeze() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. See Also: The record. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. and possesses. and possesses. See Also: The record.setflags() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.swapaxes() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. albeit unimplemented.1 Class generic exists solely to derive numpy scalars from. albeit unimplemented. and possesses. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API.sort() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented.6. albeit unimplemented. See Also: The record. See Also: 1. all the attributes of the ndarray class so as to provide a uniform API.

all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. See Also: The record.tolist() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.var() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from.NumPy Reference.1 The record. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API. albeit unimplemented. albeit unimplemented.8. See Also: The record. albeit unimplemented. albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API.transpose() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. and possesses.take() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. all the attributes of the ndarray class so as to provide a uniform API. and possesses. See Also: The record. See Also: The record.tofile() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. Release 1. See Also: The record. See Also: The record. and possesses.tostring() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. and possesses. and possesses.trace() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. all the attributes of the ndarray class so as to provide a uniform API. 226 Chapter 1. Array objects . albeit unimplemented. all the attributes of the ndarray class so as to provide a uniform API.

ma) See Also: Masked arrays 1. Multiple inheritance is probably easier with numpy.1 See Also: The record.lib. Release 1.user_array.NumPy Reference. numpy.user_array.8..container than with the ndarray itself and so it is included by default.tostring() 1. all the attributes of the ndarray class so as to provide a uniform API.container(data[.container The container class is a Python class whose self. Standard array subclasses 227 .container(data.6.6 Masked arrays (numpy.lib.]) class numpy..byteswap() container.lib. albeit unimplemented. It is not documented here beyond mentioning its existence because you are encouraged to use the ndarray class directly if you can.6.array attribute is an ndarray. copy=True) Methods astype(typecode) byteswap() copy() tostring() container.copy() container. and possesses.6. See Also: The 1. .lib. the UserArray from Numeric has been brought over to NumPy and named numpy.user_array.astype(typecode) container.view() Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from. dtype=None.user_array.7 Standard container class For backward compatibility and as a standard “container “class.

2. To loop over the entire array requires N for-loops. Array objects . which acts similarly to.reshape(2..NumPy Reference.8.flat A 1-D iterator over the array. This is a numpy. calls val = myiter. >>> a = arange(24).flatiter instance. There are several ways to iterate over an array that may be useful: default iteration.. 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 ndarray.. This can be a useful construct for defining recursive algorithms. when the array object itself is used as an iterator.8 Array Iterators Iterators are a powerful concept for array processing. The default behavior is equivalent to: for i in range(arr.. flat iteration. See Also: flatten Return a copy of the array collapsed into one dimension. 3) >>> x 228 Chapter 1. Release 1. then the Python code: for val in myiter: . Default iteration The default iterator of an ndarray object is the default Python iterator of a sequence type.arange(1.flat A 1-D iterator over the array..6. If myiter is an iterator object.. and N -dimensional enumeration.next() repeatedly until StopIteration is raised by the iterator.reshape(3. Python’s built-in iterator object. Thus. some code involving val . but is not a subclass of. ndarray.4)+10 >>> for val in a: . print ’item:’.shape[0]): val = arr[i] This default iterator selects a sub-array of dimension N − 1 from the array.1 1. Essentially. iterators implement a generalized for-loop. flatiter Examples >>> x = np. 7).

4]]) >>> for index. 3. 5. >>> for i. 3]. Return an iterator yielding pairs of array coordinates and values. 3]. x array([[3.. 3. N-dimensional enumeration ndenumerate(arr) Multidimensional index iterator. 2.ndenumerate(arr) Multidimensional index iterator.flat[3] 5 >>> type(x..flat = 3..1 array([[1. 6]]) >>> x. [3. [3. [3.4]] = 1.T array([[1. 1.flat) <type ’numpy. 3]]) As mentioned previously. Standard array subclasses 229 . x 1.flatiter’> An assignment example: >>> x. the flat attribute of ndarray objects returns an iterator that will cycle over the entire array in C-style contiguous order. [4.NumPy Reference. 6]]) >>> x.T.flat[3] 4 >>> x.. 1. I’ve used the built-in enumerate iterator to return the iterator index as well as the value.8. 3]]) >>> x. 2]. val 0 10 5 15 10 20 15 25 20 30 Here. See Also: ndindex. x in np. class numpy. [2.flat[[1.ndenumerate(a): . 4]. print index. 3]. 5].flat): . val in enumerate(a.array([[1. Release 1. if i%5 == 0: print i. Parameters a : ndarray Input array. [3. flatiter Examples >>> a = np.6. x array([[3.

class numpy. (1. Returns b : broadcast object Broadcast the input parameters against one another. Examples Manually adding two vectors.8. val : scalar The array element of the current iteration.broadcast(x. (2. The ndenumerate iterator can achieve this. returns the index tuple and array value.broadcast Produce an object that mimics broadcasting. Release 1. in2. 3) 29 1.. (0. . 5. Array objects . val in ndenumerate(a): if sum(i)%5 == 0: print i. y) 230 Chapter 1. it has shape and nd properties. 2) 32 Iterator for broadcasting broadcast Produce an object that mimics broadcasting. val 0. 3) 25 0. 0) 1) 0) 1) 1 2 3 4 Methods next() Standard iterator method. Amongst others. (1. 6]) >>> b = np. (2. using broadcasting: >>> x = np.next() Standard iterator method... 0) 10 1.array([4. [2]. for i. Parameters in1. Sometimes it may be useful to get the N-dimensional index while iterating. ndenumerate. returns the index tuple and array value. Returns coords : tuple of ints The indices of the current iteration. (0.NumPy Reference.1 (0. >>> .array([[1].. [3]]) >>> y = np. (1. and may be used as an iterator. : array_like Input parameters. and return an object that encapsulates the result.

.]]) Compare against built-in broadcasting: >>> x + y array([[5. [6. y) row. 2.index current index in broadcasted result Examples >>> x = np. Release 1. (1.8.next().” Returns a tuple of numpy.array([1.broadcast(x. 7..next(). x = np.index 0 >>> b. 6]) >>> b = np.NumPy Reference.array([[4]. 9]]) Attributes index iters shape size current index in broadcasted result tuple of iterators along self‘s “components. Total size of broadcasted result.iters row.v) in b] >>> out array([[ 5.flatiter objects. y) >>> b. [ 6.].flatiter Examples >>> >>> >>> >>> >>> (1. Standard array subclasses 231 .next() 4) broadcast. 6. 7. col = b. col. 5). 8.shape Shape of broadcasted result.... 6)) >>> b.iters tuple of iterators along self‘s “components.” Shape of broadcasted result.array([4. one for each “component” of self. 8.array([[1]. [5].index 3 broadcast. broadcast. b.]. 8].broadcast(x. [7.shape) >>> out. (1. 1. 3]) y = np. 6.empty(b. 8. [6]]) b = np. [2]. 4).flat = [u+v for (u. 7. 5.6. 7]. See Also: numpy.next().next() ((1. b. [3]]) >>> y = np.1 >>> out = np. 9.. [ 7.

3]) y = np.1 Examples x = np.broadcast(x. 2. [5].[0.reset() >>> b. (3. 4)) >>> b.reset() Reset the broadcasted result’s iterator(s). or raise StopIteration Reset the broadcasted result’s iterator(s). or raise StopIteration broadcast.index 0 The general concept of broadcasting is also available from Python using the broadcast iterator.broadcast(x. 0) (0.0]. [6]] >>> b = np. 4). Parameters None Returns None Examples >>> x = np.next() -> the next value. 1) 232 Chapter 1. broadcast. Examples x = np. print val (1.next() -> the next value.size Total size of broadcasted result. 3]) y = np. [5]. 3]) >>> y = np. [6]]) b = np..index 0 >>> b. b. y) b. (2.next x. broadcast. b. y) >>> b.next().array([[4].[2. Release 1.broadcast(x.index 3 >>> b. 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.next().size >>> >>> >>> >>> 9 Methods next reset() x.array([[4].next() ((1.NumPy Reference. y) b. [6]]) b = np. 2. >>> for val in broadcast([[1. Array objects .. 4).array([1.8. [5]. 2.shape 3) >>> >>> >>> >>> (3.array([1.1]): .3]].array([1.array([[4].

As an illustration. The numpy. 2. A mask is either nomask. When an element of the mask is False.1 (2. The numpy.7. Masked arrays 233 . The numpy. 1.ma module The main feature of the numpy. its attributes and methods are described in more details in the MaskedArray class section. a sensor may have failed to record a data. When an element of the mask is True. mask=[0.ma module can be used as an addition to numpy: >>> import numpy as np >>> import numpy. 1. 5]) We wish to mark the fourth entry as invalid.masked_array(x. The class. -1. datasets can be incomplete or tainted by the presence of invalid data.8.7.ndarray and a mask.ma as ma >>> x = np.ma module is the MaskedArray class.ma as ma 1. The easiest is to create a masked array: >>> mx = ma.ma module provides a convenient way to address this issue. which is a subclass of numpy.ma module provides a nearly workalike replacement for numpy that supports data arrays with masks. For example. What is a masked array? In many circumstances.mean() 2. or recorded an invalid value.array([1. 0]) We can now compute the mean of the dataset. 0.75 The numpy. the corresponding element of the associated array is said to be masked (invalid).ma module provides a nearly workalike replacement for numpy that supports data arrays with masks. 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. The package ensures that masked entries are not used in computations.NumPy Reference.7 Masked arrays Masked arrays are arrays that may have missing or invalid entries.ma module Rationale Masked arrays are arrays that may have missing or invalid entries. 3. let’s consider the following dataset: >>> import numpy as np >>> import numpy. without taking the invalid data into account: >>> mx. A masked array is the combination of a standard numpy. the corresponding element of the associated array is valid and is said to be unmasked.ndarray. The numpy. Release 1. 1) 1. 0. by introducing masked arrays.1 The numpy. 0) (3.

If dtype is None. order. subok=True. keep_mask=True. Release 1. An array class with possibly masked values. mask=nomask.array([1. array and masked_array. 1. dtype. Default is True. • A first possibility is to directly invoke the MaskedArray class. dtype=None. copy. ndmin=0) An array class with possibly masked values. hard_mask=False. mask : sequence. copy : bool.1 To create an array with the second element invalid.NumPy Reference. 1. numpy.e20. 3. . Default is False. If dtype is not None and different from data. mask = [0. subok : bool. we would do: >>> z = masked_values([1. a copy is performed. 3]. we would do: >>> y = ma.]) masked_array An array class with possibly masked values. • A second possibility is to use the two masked array constructors.. Masked values of True exclude the corresponding element from any computation. 1. ndmin=0. fill_value=None. fill_value=None. mask.8. 2. dtype : dtype.0. or to use a reference instead. optional Mask.2 Using numpy. dtype=None. shrink=True) Parameters data : array_like Input data. copy=False.e20 are invalid.e. invalid) data. optional Data type of the output.0. array(data[.dtype.ma. Must be convertible to an array of booleans with the same shape as data.. keep_mask=True. subok=True. True indicates a masked (i. optional Whether to return a subclass of MaskedArray if possible (True) or a plain MaskedArray.0]. shrink=True. Construction: x = MaskedArray(data. mask=False.dtype) is used.e20) For a complete discussion of creation methods for masked arrays please see section Constructing masked arrays.7. 4.ma Constructing masked arrays There are several ways to construct a masked array. copy=False. 1. hard_mask=None.array(data. Array objects . order=False. ndmin : int. optional Whether to copy the input data (True). 0]) To create a masked array where all values close to 1. optional 234 Chapter 1. the type of the data argument (data.

Mask an array outside a given interval.view(ma. In that case. copy]) masked_invalid(a[. 1. False) (False.int). dtype]) fix_invalid(a[. 2. optional Whether to force compression of an empty mask. dtype. copy]) masked_values(x. value[. Convert the input to a masked array. Mask an array where less than a given value. Mask an array where less than or equal to a given value. value[. shrink]) masked_outside(x.7. Mask an array where greater than or equal to a given value. numpy. . 1. copy]) masked_greater(x. float)]) >>> x. optional Whether to combine mask with the mask of the input data. False)].MaskedArray) masked_array(data = [1 2 3]. atol. 2. mask. v1. copy. v2[. 1. dtype=[(’a’. dtype = [(’a’. Mask an array where a condition is met.1 Minimum number of dimensions. conserving subclasses. 1e+20). or to use only mask for the output (False). fill_value = 999999) >>> x = np. rtol.NumPy Reference.0) (2. v2[. shrink : bool.array([1.asarray(a. mask = [(False. dtype=None. Mask an array where invalid values occur (NaNs or infs). With a hard mask.masked_array alias of MaskedArray • A third option is to take the view of an existing array.ma. Masked arrays 235 .). copy]) masked_greater_equal(x. 2. Mask an array where greater than a given value. copy. optional Value used to fill in the masked values when necessary. hard_mask : bool. Mask an array inside a given interval. Release 1.0)]. >>> x = np. copy]) masked_less_equal(x. Default is True. order=None) Convert the input to a masked array of the given data-type.. masked values cannot be unmasked.array([(1. fill_value]) masked_equal(x.ma. copy]) masked_less(x. keep_mask : bool. a default based on the data-type is used.]) masked_where(condition. optional Whether to use a hard mask or not. value[. fill_value = (999999. if any (True). copy]) masked_inside(x. or an array of boolean with the same structure as the array otherwise. copy]) Convert the input to a masked array of the given data-type. the mask of the view is set to nomask if the array has no named fields. Mask the array x where the data are exactly equal to value.. (’b’. value[. value[. Mask an array where not equal to a given value. value[.MaskedArray) masked_array(data = [(1.)]. fill_value : scalar. value[. Default is 0. ’<i4’). copy. Default is True. Return input with invalid data masked and replaced by a fill value. v1. (2. copy]) masked_not_equal(x.8. If None. 3]) >>> x. numpy. copy]) masked_object(x. a[. ’<f8’)]) • Yet another possibility is to use any of the following functions: asarray(a[. Mask using floating point equality. Mask an array where equal to a given value.view(ma. order]) asanyarray(a[. (’b’. mask = False. Default is False. value[.

).asarray(x) masked_array(data = [[ 0. 1...]]) >>> np. Release 1. optional By default. Returns out : MaskedArray Masked array interpretation of a. 5) >>> x array([[ 0.1 No copy is performed if the input is already an ndarray. dtype=None) Convert the input to a masked array. fill_value = 1e+20) >>> type(np. 3. 1.. its class is conserved. 7.8.. ‘F’}. in any form that can be converted to a masked array.MaskedArray’> numpy.reshape(2. Array objects .. 2. lists of tuples.] [ 5. tuples of tuples. conserving subclasses. 8. 4.]]. optional By default. mask = False. This includes lists.]. [ 5.. 6. ndarrays and masked arrays. dtype : dtype. See Also: asanyarray Similar to asarray.core. 236 Chapter 1. Examples >>> x = np.. order : {‘C’.NumPy Reference.asarray(x)) <class ’numpy. but conserves subclasses. order : {‘C’. optional Whether to use row-major (‘C’) or column-major (‘FORTRAN’) memory representation.arange(10. tuples. ‘F’}. 9.ma. 7. 4. optional Whether to use row-major (‘C’) or column-major (‘FORTRAN’) memory representation. the data-type is inferred from the input data. Default is ‘C’. a base class MaskedArray is returned. 2. If a is a subclass of MaskedArray. If a is a subclass of MaskedArray. the data-type is inferred from the input data. 9. No copy is performed if the input is already an ndarray.ma.ma. in any form that can be converted to an array. 8.asanyarray(a. 3. Parameters a : array_like Input data.ma. dtype : dtype. 6. Default is ‘C’. Parameters a : array_like Input data.. tuples of lists.

] [ 5. 2. Notes A copy is performed by default. 9. np. mask=[1] + [0]*3) >>> x masked_array(data = [-. Masked arrays 237 . See Also: asarray Similar to asanyarray. Examples >>> x = np.ma.7.fix_invalid(a.-1.0 nan inf]. mask = [ True False False False]..arange(10. 5) >>> x array([[ 0. etc.ma. in which case the a. optional Value used for fixing invalid data. Default is True.]]) >>> np.asanyarray(x)) <class ’numpy. inf. [ 5. Parameters a : array_like Input array..array([1.ma. but does not conserve subclass. copy=True.. 7. Release 1. Invalid data means values of nan. fill_value = 1e+20) >>> np. 3..8.1 Returns out : MaskedArray MaskedArray interpretation of a. fill_value : scalar. mask = False.ma... np.fix_invalid(x) 1. Examples >>> x = np.]].reshape(2.inf]. Default is None. 4. copy : bool. Returns b : MaskedArray The input array with invalid entries fixed. 8.core. mask=False. optional Whether to use a copy of a (True) or to fix a in place (False). 8. 6. 7.asanyarray(x) masked_array(data = [[ 0. 1. a (subclass of) ndarray...]. 9.MaskedArray’> numpy.nan.NumPy Reference. 2.ma. 1. 6.).fill_value is used. 3. fill_value = 1e+20) >>> type(np. 4. fill_value=None) Return input with invalid data masked and replaced by a fill value. -1.ma..

value).00000000e+20]) >>> x.masked_greater(x. numpy. 1.-1. consider using masked_values(x. 1. Array objects . This function is a shortcut to masked_where.arange(4) >>> a array([0.00000000e+00.NumPy Reference. mask = [False False False fill_value=999999) True]. masked_values Mask using floating point equality.8. Examples >>> import numpy. with condition = (x > value).0 -. numpy. fill_value=999999) numpy. -1. value.3]. 2) masked_array(data = [0 1 -. copy=True) Mask an array where greater than a given value.data array([ 1. See Also: masked_where Mask where a condition is met. 3]) >>> ma.. value. value.fix_invalid(x) >>> fixed. Inf]) 1.00000000e+00. copy=True) Mask an array where greater than or equal to a given value.ma as ma >>> a = np.masked_equal(x. 2) masked_array(data = [0 1 2 --]. copy=True) Mask an array where equal to a given value. mask = [ True False True fill_value = 1e+20) True]. This function is a shortcut to masked_where. 3]) >>> ma.1 masked_array(data = [-.--]. 2. >>> fixed = np. See Also: masked_where Mask where a condition is met. For floating point arrays. 238 Chapter 1.ma as ma >>> a = np.ma. Release 1.ma.masked_greater(a.ma. Examples >>> import numpy.masked_equal(a.00000000e+20.ma. 2.masked_greater_equal(x. NaN.arange(4) >>> a array([0. mask = [False False True False]..data array([ 1. 1. -1. with condition = (x == value).

1].isfinite(a)).1 This function is a shortcut to masked_where.4 -1.-0.4. See Also: masked_where Mask where a condition is met.--]. See Also: masked_where Mask where a condition is met. mask = [False False True True False False].3) masked_array(data = [0. 0. mask = [False False True True]. Examples >>> import numpy. fill_value=999999) numpy. Release 1. Only applies to arrays with a dtype where NaNs or infs make sense (i. 0. 1.-0. floating point types).31 1. fill_value=1e+20) numpy.-. 0.31.01.masked_inside(x. where condition is True for x inside the interval [v1.3.1] >>> ma.2. but accepts any array_like object.masked_invalid(a. Examples >>> import numpy. Any pre-existing mask is conserved. v1.4 -1. mask = [False False True True False False].3) masked_array(data = [0. -0. See Also: masked_where Mask where a condition is met. with condition = ~(np. 2) masked_array(data = [0 1 -. 0.2 -. 1. fill_value=1e+20) The order of v1 and v2 doesn’t matter. 3]) >>> ma.1]. This function is a shortcut to masked_where.8. copy=True) Mask an array where invalid values occur (NaNs or infs).ma as ma >>> x = [0.2.masked_greater_equal(a.ma.v2] (v1 <= x <= v2). 1.arange(4) >>> a array([0. -0.7. -1. copy=True) Mask an array inside a given interval.2 -. v2. 2. Shortcut to masked_where. -0.masked_inside(x. Masked arrays 239 . with condition = (x >= value).NumPy Reference.masked_inside(x.3. Notes The array x is prefilled with its filling value. The boundaries v1 and v2 can be given in either order.e.ma as ma >>> a = np.-. >>> ma.ma.31 1.

Inf.]) >>> ma.NumPy Reference. Examples >>> import numpy.masked_less_equal(x.ma. 2. fill_value=1e+20) numpy.-.arange(5. 1.ma. 3]) >>> ma. 4. 3]) >>> ma.masked_less(x. See Also: masked_where Mask where a condition is met.-.NaN >>> a[3] = np. with condition = (x <= value).masked_less_equal(a. 1. 1. dtype=np. Examples >>> import numpy. 2) masked_array(data = [-.arange(4) >>> a array([0.masked_not_equal(x.0]. 2) masked_array(data = [-. copy=True) Mask an array where less than or equal to a given value.ma as ma >>> a = np. This function is a shortcut to masked_where. copy=True) Mask an array where less than a given value. with condition = (x != value).0 -. mask = [ True True False False].4.0 1. Array objects .8.-. copy=True) Mask an array where not equal to a given value.arange(4) >>> a array([0.masked_less(a. fill_value=999999) numpy.ma.ma as ma >>> a = np.masked_invalid(a) masked_array(data = [0. See Also: masked_where Mask where a condition is met. Release 1.. See Also: 240 Chapter 1.3]. NaN. This function is a shortcut to masked_where.ma as ma >>> a = np. value.2 3]. value. mask = [False False True True False].-. value. mask = [ True True True False]. fill_value=999999) numpy.float) >>> a[2] = np.1 Examples >>> import numpy. with condition = (x < value).PINF >>> a array([ 0. This function is a shortcut to masked_where.. 2.

2 --].masked_object(x. optional Whether to return a copy of x. Release 1.arange(4) >>> a array([0.masked_object(food. masked_equal Mask where equal to a given value (integers). mask = [ True True False True].1 masked_where Mask where a condition is met. Examples >>> import numpy. ’ham’. dtype=object) 1. copy=True. ’ham’].8. False}.array([’cheese’. ’green_eggs’) print eat ham] # plain ol‘ ham is boring fresh_food = np. fill_value=999999) numpy. Parameters x : array_like Array to mask value : object Comparison value copy : {True. shrink : {True. 2) masked_array(data = [-.masked_not_equal(a. dtype=object) # don’t eat spoiled food eat = ma. Examples >>> >>> >>> >>> >>> [->>> >>> import numpy. 2. masked_values Mask using floating point equality. This function is similar to masked_values. value.ma. ’pineapple’].-.ma as ma food = np. use masked_values instead. 3]) >>> ma.NumPy Reference. False}. but only suitable for object arrays: for floating point. 1. shrink=True) Mask the array x where the data are exactly equal to value.ma as ma >>> a = np. Masked arrays 241 . See Also: masked_where Mask where a condition is met.7.array([’green_eggs’. optional Whether to collapse a mask full of False to nomask Returns result : MaskedArray The result of masking x where equal to value.

0. ’green_eggs’) >>> print eat [cheese ham pineapple] Note that mask is set to nomask if possible. -1. shrink=True) Mask using floating point equality. For integers.-.0. masked where the data in array x are approximately equal to value. -0.2.01.ma. Parameters x : array_like Array to mask.masked_outside(x. 0. >>> eat masked_array(data = [cheese ham pineapple]. mask = [ True True False False True fill_value=1e+20) True].v2] (x < v1)|(x > v2).3) masked_array(data = [-. 0. rtol=1e-05. mask = False. atol=1e-08.2 -.e. where the following condition is True (abs(x . -0. Examples >>> import numpy. 1. numpy. 242 Chapter 1.01 0.3) masked_array(data = [-.2.value) <= atol+rtol*abs(value)) The fill_value is set to value and the mask is set to nomask if possible.masked_outside(x. v1.3. Notes The array x is prefilled with its filling value. Release 1. i. Shortcut to masked_where.31.4.masked_values(x.1 >>> eat = ma.masked_outside(x. The order of v1 and v2 doesn’t matter. Return a MaskedArray. 0. consider using masked_equal.NumPy Reference.8.3. mask = [ True True False False True fill_value=1e+20) True]. >>> ma.-.ma as ma >>> x = [0.masked_object(fresh_food. copy=True.01 0. Array objects . value : float Masking value. v2. -0.ma. where condition is True for x outside the interval [v1. copy=True) Mask an array outside a given interval. fill_value=?) numpy.1] >>> ma. value. See Also: masked_where Mask where a condition is met.--]. 0.--].2 -. The boundaries v1 and v2 can be given in either order.

NumPy Reference. a. 2. Returns result : MaskedArray The result of masking x where approximately equal to value. 1. 1. mask = [False True False True False]. shrink : bool.1 mask = False.masked_equal(x. >>> ma. atol : float. 1. See Also: masked_where Mask where a condition is met. mask = [False False True False False]. >>> x = np.2.ma as ma >>> x = np.5) 2.5) masked_array(data = [ 1.arange(5) >>> x array([0.masked_values(x.1. optional Whether to return a copy of x.1) masked_array(data = [1. 1. fill_value=999999) numpy. 1. 1. ]. 3]) >>> ma.8.0 -.masked_values(x. copy : bool.0 -. fill_value=1. masked_equal Mask where equal to a given value (integers).3 4]. optional Tolerance parameter (1e-8).3. Masked arrays 243 . 3.1 3. fill_value=2) >>> ma.1 rtol : float.1) Note that mask is set to nomask if possible. Release 1. copy=True) Mask an array where a condition is met. 1. 4]) >>> ma. optional Whether to collapse a mask full of False to nomask. 2) masked_array(data = [0 1 -.array([1. optional Tolerance parameter. For integers.ma. 2.1.masked_where(condition.masked_values(x. fill_value=1. 2) masked_array(data = [0 1 -.0]. 1. Examples >>> import numpy. the fill value will be different in general to the result of masked_equal.3 4].7. mask = [False False True False False].

masked_outside Mask outside a given interval. masked_less Mask where less than a given value. If False modify a in place and return a view.NumPy Reference. masked_greater Mask where greater than a given value. masked_not_equal Mask where not equal to a given value.arange(4) >>> a array([0. When condition tests floating point values for equality. Array objects . a) masked_array(data = [-. a : array_like Array to mask.3]. 3]) >>> ma.-.1 Return a as an array masked where condition is True. masked_equal Mask where equal to a given value. Release 1. 2. masked_invalid Mask invalid values (NaNs or infs). See Also: masked_values Mask using floating point equality. consider using masked_values instead. Returns result : MaskedArray The result of masking a where condition is True. Any masked values of a or condition are also masked in the output. Parameters condition : array_like Masking condition.ma as ma >>> a = np. masked_inside Mask inside a given interval.-. Examples >>> import numpy.8. 244 Chapter 1.masked_where(a <= 2. copy : bool If True (default) make a copy of a in the result. 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. 1.

’d’] >>> ma.arange(4) >>> a = ma. a) >>> c masked_array(data = [-.--]. fill_value=999999) Accessing the data The underlying data of a masked array can be accessed in several ways: 1. Release 1.1 2 3]. 1.masked_where(a == 2. >>> c = ma. mask = [False True True False].7. fill_value=999999) >>> a array([99. 2.masked_where(a == 3. b) masked_array(data = [a b -.3]. mask = [ True True True False]. b) >>> b masked_array(data = [-. mask = [ True False False False].3]. Masked arrays 245 . 3]) When condition or a contain masked values.3]. 2. >>> b = [’a’. mask = [False False True False].-. 1. a) >>> a masked_array(data = [0 1 -.masked_where(b == 0.arange(4) >>> b = ma.masked_where(a <= 2. Mask array b conditional on a. mask = [False True True False].1 -.-. copy=False) >>> c[0] = 99 >>> c masked_array(data = [99 -. ’b’.d].8. fill_value=999999) >>> a array([0.1 mask = [ True True fill_value=999999) True False]. fill_value=999999) >>> ma.3]. >>> a = np. a. fill_value=999999) >>> b = np.-.-. mask = [False False True False]. fill_value=999999) >>> c[0] = 99 >>> c masked_array(data = [99 -.masked_where(a <= 2. ’c’. b) masked_array(data = [-.NumPy Reference. fill_value=N/A) Effect of the copy argument. mask = [ True False True True]. 3]) >>> c = ma.masked_where(a == 2.

array([[1. Array objects .NumPy Reference. 2. We must keep in mind that a True entry in the mask indicates an invalid data. mask = [ True False False].ndarray or one of its subclasses. 2]. [3. • by using the getdata function. depending on the value of the baseclass attribute): >>> x. mask=[[0.8. 6]. None of these methods is completely satisfactory if some entries have been marked as invalid. Release 1. • through the __array__ method. we can use the inverse of the mask as an index. getmask(x) outputs the mask of x if x is a masked array. As a general rule. [1. and the special value nomask otherwise. The inverse of the mask can be calculated with the numpy. Accessing the mask The mask of a masked array is accessible through its mask attribute. [4. the function outputs a boolean array of False with as many elements as x. 4]) Note that the output of compressed is always 1D.1 • through the data attribute.masked >>> x masked_array(data = [-. Accessing only the valid entries To retrieve only the valid entries. which returns a one-dimensional ndarray (or one of its subclasses. 3]. 1]. fill_value = 999999) Another way to retrieve the valid data is to use the compressed method. The output is then a numpy.ndarray or one of its subclass (which is actually what using the data attribute does).2 3]. 2. [7. fill_value = 999999) >>> y = ma.logical_not function or simply with the ~ operator: >>> x = ma.array([[1.ndarray. 3]) >>> x[0] = ma. The output is a view of the array as a numpy. 0]]) >>> x[~x. Another possibility is to use the getmask and getmaskarray functions. 4]]. 5. depending on the type of the underlying data at the masked array creation. mask = [False False]. Modifying the mask 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: >>> x = ma. getmaskarray(x) outputs the mask of x if x is a masked array.compressed() array([1. • by directly taking a view of the masked array as a numpy. If x has no invalid entry or is not a masked array.array([1. 8.mask] masked_array(data = [1 4]. it is recommended to fill the array with the filled method. 9]]) 246 Chapter 1. where a representation of the array is required without any masked entries.

(1.-.array([1. non-structured datatype. as a boolean does not support item assignment. 0. 1]) >>> x.3] [4 5 --] [-. mask = [False True False].7. 1. 0] >>> x masked_array(data = [1 -. fill_value = 999999) >>> x[-1] = 5 >>> x masked_array(data = [1 2 5].1 >>> y[(0. mask=[0.3 4].mask = True >>> x masked_array(data = [-. the mask is initially set to the special value nomask. Trying to set an element of nomask will fail with a TypeError exception. Release 1. mask = [[False True False] [False False True] [ True False False]]. 4]) >>> z[:-2] = ma. mask=[0. that corresponds roughly to the boolean False.array([1. 0)] = ma. 3]. 2. but this usage is discouraged. specific entries can be masked and/or unmasked by assigning to the mask a sequence of booleans: >>> x = ma.array([1.8 9]]. fill_value = 999999) 1. we can just assign one or several new valid values to them: >>> x = ma. All the entries of an array can be masked at once by assigning True to the mask: >>> x = ma. 3]. 0. 3]) >>> x. fill_value = 999999) Unmasking an entry To unmask one or several specific entries. 2). mask = [False False True]. fill_value = 999999) A second possibility is to modify the mask directly. mask = [ True True True].masked >>> y masked_array(data = [[1 -.--]. 3. 2. 2.3].mask = [0. mask = [False False False].-. mask = [ True True False False]. Note: When creating a new masked array with a simple. 1. Masked arrays 247 . 2. fill_value = 999999) Finally. fill_value = 999999) >>> z = ma. 1]) >>> x masked_array(data = [1 2 --].masked >>> z masked_array(data = [-.array([1. 2.NumPy Reference.8.

mask=[0. 1]) >>> x[0] 1 >>> x[-1] masked_array(data = --. mask = True.array([1. fill_value = 999999) >>> x. or a 0d masked array with the same dtype as the initial array if at least one of the fields is masked. 3]. 0.1 Note: Unmasking an entry by direct assignment will silently fail if the masked array has a hard mask.array([1. It can be re-hardened with harden_mask: >>> x = ma. mask=[0. as shown by the hardmask attribute.masked True If the masked array has named fields. fill_value = 999999) >>> x. mask = [False False True]. accessing a single entry returns a numpy. 2.8.mask = ma. fill_value = 999999) >>> x. 3]. mask = [False False True]. mask = [False False True]. it inherits its mechanisms for indexing and slicing. hard_mask=True) >>> x masked_array(data = [1 2 --]. the simplest solution is to assign the constant nomask to the mask: >>> x = ma. Release 1. 2.NumPy Reference.ndarray.array([1. fill_value = 999999) Indexing and slicing As a MaskedArray is a subclass of numpy. 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): >>> x = ma. When accessing a single entry of a masked array with no named fields. 2. mask=[0. 248 Chapter 1. 0. mask = [False False False]. 0. mask = [False False False]. Array objects . fill_value = 1e+20) >>> x[-1] is ma.harden_mask() To unmask all masked entries of a masked array (provided the mask isn’t a hard mask).void object if none of the fields are masked. 1]) >>> x masked_array(data = [1 2 --].soften_mask() >>> x[-1] = 5 >>> x masked_array(data = [1 2 5]. 3]. fill_value = 999999) >>> x[-1] = 5 >>> x masked_array(data = [1 2 --]. To force the unmasking of an entry where the array has a hard mask. This feature was introduced to prevent overwriting the mask. 1]. the mask must first to be softened using the soften_mask method before the allocation.nomask >>> x masked_array(data = [1 2 3].

fill_value = 1e+20) Masked arrays also support standard numpy ufuncs.3]. 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. 1. The result of a binary ufunc is masked wherever any of the input is masked.log([-1. int).array([1. 1]) >>> mx = x[:3] >>> mx masked_array(data = [1 -. True). 3. 4. 4)]. dtype=bool) >>> x. False.masked_array([(1. The output is then a masked array. The copy is required to avoid propagation of any modification of the mask to the original. The result of a unary ufunc is masked wherever the input is masked. 4. 1)]. fill_value = (999999.ma module comes with a specific implementation of most ufuncs. (’b’. mask=[0. ’<i4’).. 999999).8. True. 0). (’b’.-. (0. 0.NumPy Reference.1 >>> y = ma. Masked arrays 249 . -1. Warning: We need to stress that this behavior may not be systematic.mask array([False..7. ’<i4’)]) When accessing a slice. invalid entries of a masked array are not processed. meaning that the corresponding data entries should be the same before and after the operation. 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: >>> ma. the context is processed and entries of the output masked array are masked wherever the corresponding input fall outside the validity domain: 1.. mask = [False True False]. fill_value = 999999) >>> mx[1] = -1 >>> mx masked_array(data = [1 -1 3].69314718056]. --). . 5]. False. 2]) masked_array(data = [-. 3. dtype=[(’a’. 1. Release 1. mask = [ True True False False]. . 0. The numpy.data array([ 1.2). (3. 5]) Accessing a field of a masked array with structured datatype returns a MaskedArray. fill_value = 999999) >>> x. mask = (False. 0. If the ufunc also returns the optional context output (a 3-element tuple containing the name of the ufunc. >>> x = ma. As much as possible. mask = [False True False].. Operations on masked arrays Arithmetic and comparison operations are supported by masked arrays. 2) >>> y[-1] masked_array(data = (3. mask=[(0. its arguments and its domain). that masked data may be affected by the operation in some cases and therefore users should not rely on this data remaining unchanged.0. the output is a masked array whose data attribute is a view of the original data. int)]) >>> y[0] (1. 2. True].0 0. dtype = [(’a’.

0]) >>> y = ma.0] Filling in the missing data Suppose now that we wish to print that same data.9]: >>> print ma.--] Four values of the output are invalid: the first one comes from taking the square root of a negative number. We wish to compute the average value of the data and the vector of anomalies (deviations from the average): >>> import numpy. 2. 0. 5.7.0.mean() 2. -9999. 0.-.log(x) masked_array(data = [-.. where values of -9999. represent missing data.0.1.mean() 250 Chapter 1. etc. 0.mx.filled(mx.] Numerical operations Numerical operations can be easily performed without worrying about missing values.0 -. 1.. 4. 6.NumPy Reference.1]) >>> print np.array([1.masked_outside(d.0 -1.: >>> import numpy as np. -1.4.1 >>> x = ma.3 Examples Data with a given value representing missing data Let’s consider a list of elements..mean() [-2.. x. and the last two where the inputs were masked.ma as ma >>> x = [0. 4.ma as ma >>> x = ma.array([1.0 0. Ignoring extreme values Let’s consider an array d of random floats between 0 and 1. mask=[0..) >>> print mx.0 -1. We wish to compute the average of the values of d while ignoring any data outside the range [0.-9999. 4. 3]. 0.1.0.0.]. 0. 6.0. 2.mean()) [ 0.. mask=[0.0.anom() [-2. 3.0 2..1.0 2.69314718056 --].1.1.sqrt(x/y) [1. Release 1. dividing by zero.0 -. Array objects ... mask=[0.1.-. the second from the division by zero. numpy... mask = [ True True False False True].1. 0. 2.]. 3.0 >>> print mx . fill_value = 1e+20) 1. 1.masked_values (x.. 5..3.8.] >>> mx = ma. 1]) >>> np. 0.0.0. square roots of negative numbers..0 -. >>> print mx.0 -.9).0] >>> print mx. 0.array([-1. but with the missing values replaced by the average value.

ma module defines several constants. 1].array([1. [3. where a True value indicates that the corresponding element of the data is invalid. 2. 1.1 1.masked >>> x masked_array(data = [1 -.NumPy Reference.nomask Value indicating that a masked array has no invalid entry.7.8. 0]]) >>> x. 3].data Returns the underlying data. 1. Release 1. mask=[0.masked_print_options String used in lieu of missing data when a masked array is printed.--].ma module In addition to the MaskedArray class. The special value nomask is also acceptable for arrays without named fields. as a regular numpy.masked The masked constant is a special case of MaskedArray. 1. 0]) >>> x[1] is ma.7.ma. An instance of MaskedArray can be thought as the combination of several elements: • The data. It is used to test whether a specific entry of a masked array is masked.MaskedArray A subclass of ndarray designed to manipulate numerical arrays with missing data. and indicates that no data is invalid. as a view of the masked array. 2]. with a float datatype and a null shape. or to mask one or several entries of a masked array: >>> x = ma. mask=[[0. 2]. a value that may be used to replace the invalid entries in order to return a standard numpy. fill_value = 999999) numpy. By default. [3.array(np. mask = [False True True].matrix([[1.ndarray.ma. 4]]) The type of the data can be accessed through the baseclass attribute. numpy.5 The MaskedArray class class numpy.ndarray of any shape or datatype (the data). numpy. [1.masked True >>> x[-1] = ma. it is returned as such. the numpy. • A boolean mask with the same shape as the data. this string is ’--’. • A fill_value.ma.7. If the underlying data is a subclass of >>> x = ma.ndarray. nomask is used internally to speed up computations when the mask is not needed. numpy. Masked arrays 251 .ma. 4]]).4 Constants of the numpy. Attributes and properties of masked arrays See Also: Array Attributes MaskedArray.data matrix([[1.

matrix’> MaskedArray. 2). 0]. mask=[(0. (3. any modification to the mask of one array will be propagated to the others.e20+0j ‘?’ ‘N/A’ MaskedArray.shape MaskedArray.e20 1. masked entries cannot be unmasked. . (1. 1). The value is either a scalar (if the masked array has no named fields). 5)].ndim MaskedArray. dtype=bool) MaskedArray. The default filling value depends on the datatype of the array: datatype bool int float complex object string default True 999999 1.fill_value Returns the value used to fill the invalid entries of a masked array. 1). returns a ndarray of booleans where entries are True if all the fields are masked. int).defmatrix. 0).dtype MaskedArray. Tuple of bytes to step in each dimension when traversing an array. Number of elements in the array. Continued on next page Chapter 1. but where all fields are atomically booleans.array([(1.strides MaskedArray. 0)].matrix([[1.flags MaskedArray. 0]]) >>> x.size MaskedArray.NumPy Reference. >>> x = ma. a masked array also inherits all the attributes and properties of a ndarray instance.. For structured arrays. (0. False]. Information about the memory layout of the array. Imaginary part.base MaskedArray. A value of True indicates an invalid entry. mask=[[0. (2. True.nbytes MaskedArray. When the mask is hard. (0. int)]) >>> x.imag 252 Base object if memory is from some other object.1 MaskedArray.8. Total bytes consumed by the elements of the array.itemsize MaskedArray. 3). Release 1.. . Number of array dimensions. If this is the case. False. 4]]). 4).baseclass <class ’numpy. MaskedArray. or a 0-D ndarray with the same dtype as the masked array if it has named fields. [1.. as an array with the same shape and structure as the data. (’b’.sharedmask Returns whether the mask of the array is shared between several masked arrays.matrixlib.recordmask array([False.ctypes MaskedArray. 0).hardmask Returns whether the mask is hard (True) or soft (False). [3. MaskedArray.recordmask Returns the mask of the array if it has no named fields.mask Returns the underlying mask. (5. False otherwise: >>> x = ma. Array objects ..baseclass Returns the class of the underlying data. As MaskedArray is a subclass of ndarray.array(np. False. (4. 1). 2]. An object to simplify the interaction of the array with the ctypes module. Tuple of array dimensions. Length of one array element in bytes. Data-type of the array’s elements. (1. dtype=[(’a’. MaskedArray.

whose memory is shared with x: >>> y = x[2:] >>> y. Release 1.2. •shape (c_intp*self. This attribute creates an object that makes it easier to use arrays when calling shared libraries with the ctypes module.1 Table 1. This ctypes array contains the strides information from the underlying array. Masked arrays 253 .61 – continued from previous page MaskedArray.ctypeslib Notes Below are the public attributes of this object which were documented in “Guide to NumPy” (we have omitted undocumented public attributes.8.base Base object if memory is from some other object. 1.ndim where the basetype is the C-integer corresponding to dtype(‘p’) on this platform. etc.7.ctypes An object to simplify the interaction of the array with the ctypes module.NumPy Reference. This base-type could be c_int. c_long.4]) >>> x. and strides attributes (see Notes below) which themselves return ctypes objects that can be used as arguments to a shared library. See Also: numpy. MaskedArray. Parameters None Returns c : Python object Possessing attributes data. Examples The base of an array that owns its memory is None: >>> x = np. User Beware! The value of this attribute is exactly the same as self. The ctypes array contains the shape of the underlying array. as well as documented private attributes): •data: A pointer to the memory area of the array as a Python integer. data. 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.ndim where the basetype is the same as for the shape attribute.3. The memory area may not even be writeable.ndim): A ctypes array of length self. This memory area may contain data that is not aligned.ctypeslib.ndim): A ctypes array of length self. or c_longlong depending on the platform. among others. strides. •strides (c_intp*self. The returned object has.array([1. This strides information is important for showing how many bytes must be jumped to get to the next element in the array.flat Flat version of the array. The c_intp type is defined accordingly in numpy. shape. or not in correct byte-order.__array_priority__ int(x=0) -> int or long MaskedArray.real Real part MaskedArray.base is x True MaskedArray. shape.base is None True Slicing creates a view._array_interface_[’data’][0].

ctypes.c_double)).ctypes.ctypes._as_parameter_ is equivalent to self.ctypes. Perhaps you want to use the data as a pointer to a ctypes array of floating-point data: self.data_as(ctypes.contents c_long(0) >>> x. For example: •strides_as(obj): Return the strides tuple as an array of some other c-types type.ctypes.strides <numpy._internal.ctypes.ctypes.especially on temporary arrays or arrays constructed on the fly.POINTER(ctypes. 1].c_long)) <ctypes.data 30439712 >>> x.dtype Examples >>> x array([[0. •shape_as(obj): Return the shape tuple as an array of some other c-types type._internal.strides_as(ctypes.c_short). ct will hold a reference to the array until ct is deleted or re-assigned.c_longlong)). Examples >>> import ctypes >>> x array([[0.core.c_longlong).c_long_Array_2 object at 0x01FFD580> >>> x.data_as(ctypes.dtype Data-type of the array’s elements. then the ctypes attribute of array objects still returns something useful.POINTER(ctypes. self. [2. 3]]) >>> x.core. If the ctypes module is not available.core.strides_as(ctypes.ctypes.NumPy Reference. Array objects .core. [2. calling (a+b).c_long_Array_2 object at 0x01FCE620> >>> x. For example. calling self. 1]. 3]]) 254 Chapter 1.POINTER(ctypes.1 •data_as(obj): Return the data pointer cast to a particular c-types object. the object will still have the as parameter attribute which will return an integer equal to the data attribute.LP_c_long object at 0x01F01300> >>> x. but ctypes objects are not returned and errors may be raised instead.POINTER(ctypes.c_longlong) <numpy.8.data_as(ctypes.data_as(ctypes. For example.c_long)). For example: Be careful using the ctypes attribute . In particular.shape_as(ctypes. In the latter case.shape <numpy.data_as(ctypes. Parameters None Returns d : numpy dtype object See Also: numpy. You can avoid this problem using either c=a+b or ct=(a+b).c_long_Array_2 object at 0x01FCE620> >>> x.contents c_longlong(4294967296L) >>> x.c_longlong_Array_2 object at 0x01F01300> MaskedArray.c_long) <numpy.data_as(ctypes. Release 1. self.shape_as(ctypes._internal.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._internal.ctypes.ctypes.c_void_p).

Release 1. •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.setflags. It does not generally hold that self.strides[-1] == self.itemsize for Fortran-style contiguous arrays is true.itemsize for C-style contiguous arrays or self. or by using lowercased attribute names (as in a. This is clear for 1-dimensional arrays. Only the UPDATEIFCOPY. •ALIGNED can only be set True if the data is truly aligned. but can also be true for higher dimensional arrays. 1. The array flags cannot be set arbitrarily: •UPDATEIFCOPY can only be set False.dtype) <type ’numpy.1 >>> x. via direct assignment to the attribute or dictionary entry.shape[dim] == 1 or the array has no elements.NumPy Reference.writeable). Short flag names are only supported in dictionary access. and ALIGNED flags can be changed by the user. Even for contiguous arrays a stride for a given dimension arr.strides[0] == self.flags Information about the memory layout of the array.dtype dtype(’int32’) >>> type(x.flags[’WRITEABLE’]). Arrays can be both C-style and Fortran-style contiguous simultaneously.dtype’> MaskedArray. Notes The flags object can be accessed dictionary-like (as in a.strides[dim] may be arbitrary if arr. or by calling ndarray.7. Masked arrays 255 .flags. WRITEABLE.8.

Fortran-style contiguous segment.3].itemsize 480 256 Chapter 1. the base array will COPY be updated with the contents of this array. currently.itemsize x = np. etc. Setting this to False locks the data.complex128) >>> x. (B) CARRAY BEHAVED and C_CONTIGUOUS.2). Notes Does not include memory consumed by non-element attributes of the array object. (C) F_CONTIGUOUS The data is in a single. (FA) MaskedArray. dtype=np. Array objects . (F) OWNDATA The array owns the memory it uses or borrows it from another object. Examples >>> >>> 8 >>> >>> 16 x = np.zeros((3. (A) UPDATEIF. Examples >>> x = np.array([1.itemsize Length of one array element in bytes.NumPy Reference. dtype=np. C-style contiguous segment. (U) FNC F_CONTIGUOUS and not C_CONTIGUOUS.3]. However. making it read-only. dtype=np. in that a view of a locked array may not be made writeable.2. A ABLE view (slice.) inherits WRITEABLE from its base array at creation time. BEHAVED ALIGNED and WRITEABLE. locking a base object does not lock any views that already reference it.nbytes 480 >>> np.2.5.float64) x.This array is a copy of some other array.prod(x. so under that circumstance it is possible to alter the contents of a locked array via a previously created writeable view onto it.nbytes Total bytes consumed by the elements of the array. FORC F_CONTIGUOUS or C_CONTIGUOUS (one-segment test). ALIGNED The data and all elements are aligned appropriately for the hardware.array([1. Release 1.complex128) x. (O) WRITEThe data area can be written to. (The opposite is not true.8. When this array is deallocated.itemsize MaskedArray.) Attempting to change a non-writeable array raises a RuntimeError exception. (CA) FARRAY BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.shape) * x. but a view of a (W) writeable array may be subsequently locked while the base array remains writeable.1 Attributes C_CONTIGUOUS The data is in a single.

prod(a..]]) unchanged MaskedArray. as long as this would not require a change in the total number of elements Examples >>> x = np. 0. See Also: numpy.ndim Number of array dimensions.. 0. .complex128) >>> x. 0. 3..stride_tricks. 0..shape = (3.8. 8) >>> y array([[ 0.strides) A more detailed explanation of strides can be found in the “ndarray.. 6) Traceback (most recent call last): File "<stdin>". Masked arrays 257 . 4)) y.zeros((2. 5. Release 1.) >>> y = np. in <module> ValueError: total size of new array must be 0.1 MaskedArray. 3]) x. dtype=np..zeros((3.7..shape Tuple of array dimensions. i[1]..shape). i.rst” file in the NumPy reference guide. i[n]) in an array a is: offset = sum(np.strides Tuple of bytes to step in each dimension when traversing an array.prod(x. Notes May be used to “reshape” the array. 0.ndim y = np.shape (2. 0.]. 0.size 30 >>> np. [ 0..lib. 0.shape (4.. [ 0. 0....]. 0.. 0. 4)) >>> y. 3. Equivalent to np. 0.array([1. 4]) >>> x... 2.e.shape) 30 MaskedArray.. Examples >>> >>> 1 >>> >>> 3 x = np.ndim MaskedArray.... 0. the product of the array’s dimensions.size Number of elements in the array.zeros((2. 4) >>> y..array(i) * a. 0. 2).... >>> y. The byte offset of element (i[0].as_strided 1. line 1. 0. 0.array([1. 3. 2. 0.NumPy Reference. Examples >>> x = np. 3. 0.shape = (3. 0. 0..

array([[0. 18. 23]]]) >>> y.reshape(np. dtype=np. 9. 1. 4.2. Examples >>> y = np. 9]].5. 2. 5. 4].4)) >>> y array([[[ 0. 21.real Real part MaskedArray. 7].6 MaskedArray methods See Also: Array methods 258 Chapter 1.5. 7.7. 2.1))) >>> offset/y. 4).8.1 Notes Imagine an array of 32-bit integers (each 4 bytes): x = np. [ 4. we have to skip 4 bytes (1 value) to move to the next column. As such.array([3.7.array((1.NumPy Reference. 8. (2.2. one after the other (known as a contiguous block of memory). [16.strides) >>> x[3. 224. 1. 16.strides * np.3. [20. 3.8)).transpose(2. 15].int32) This array is stored in memory as 40 bytes. 22. 11]]. the strides for the array x will be (20.__array_priority__ = 15 1.imag Imaginary part. [ 8. MaskedArray.1] 17 >>> offset=sum(y. 6.1. Array objects .strides (48.3. 19]. For example.6.reshape(np.2]) >>> offset = sum(i * x. 1344) >>> i = np.itemsize 17 >>> x = np.arange(2*3*4). [[12. [5. 10.0) >>> x. 17. 6. MaskedArray.1. 3].arange(5*6*7*8). 13.flat Flat version of the array. (5. 4) >>> y[1. 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.itemsize 813 MaskedArray. but 20 bytes (5 values) to get to the same position in the next row. 14.strides (32.1. Release 1.2] 813 >>> offset / x.

toflex() MaskedArray. MaskedArray. New view of array with the same data.filled([fill_value]) MaskedArray.__oct__() <==> oct(x) MaskedArray. Transforms a masked array into a flexible-type array. type=None) New view of array with the same data. MaskedArray. Transforms a masked array into a flexible-type array. Notes a.) This does not cause a reinterpretation 1. This can cause a reinterpretation of the bytes of memory. Release 1.__oct__() <==> oct(x) MaskedArray.8. float32 or int16.byteswap(inplace) MaskedArray. Save a masked array to a file in binary format.torecords() MaskedArray.__hex__() <==> hex(x) MaskedArray.__float__() Convert to float. format]) MaskedArray. This argument can also be specified as an ndarray sub-class. MaskedArray. Return a copy of self.tofile(fid[. None. optional Type of the returned view. Returns a copy of the MaskedArray cast to given newtype. Swap the bytes of the array elements Return all the non-masked data as a 1-D array.1 Conversion MaskedArray.g..view(ndarray_subclass) or a.tostring([fill_value. e. Convert to int. etc. a. e. Parameters dtype : data-type or ndarray sub-class. optional Data-type descriptor of the returned view. the default None results in type preservation.NumPy Reference. ndarray or matrix. which then specifies the type of the returned object (this is equivalent to setting the type parameter). type]) MaskedArray.__float__() MaskedArray. Return the data portion of the masked array as a hierarchical Python list. order]) Convert to float..view(type=ndarray_subclass) just returns an instance of ndarray_subclass that looks at the same array (same shape.view() is used two different ways: a. The default.__long__() <==> long(x) MaskedArray.view(dtype=some_dtype) constructs a view of the array’s memory with a different data-type.__long__() <==> long(x) MaskedArray.compressed() MaskedArray. dtype. type : Python type.__int__() MaskedArray.__int__() Convert to int. Again.view(some_dtype) or a.view([dtype.7.view(dtype=None. sep. with masked values filled with a given value.__hex__() <==> hex(x) MaskedArray. Masked arrays 259 . results in the view having the same data-type as a.tolist([fill_value]) MaskedArray.g.astype(newtype) MaskedArray. Return the array data as a string containing the raw bytes in the array.

For a.int8)]) Viewing array data using a different type and dtype: >>> y = x. 2]. dtype=int16) >>> y. (’b’. 3.view(dtype=np. in <module> ValueError: new type not compatible with array.. converting a regular array to a structured array). 5]].view(some_dtype). np.defmatrix.copy() 260 Chapter 1. the view may give different results.1] = 20 >>> print x [(1. etc. 10) Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices. 2].int16).matrix) >>> y matrix([[513]]. Therefore if a is C-ordered versus fortran-ordered.5. dtype=int8) >>> xv. It also depends on exactly how a is stored in memory.int8). np.int16. then the behavior of the view cannot be predicted just from the superficial appearance of a (shown by print(a)).]) Making changes to the view changes the underlying array >>> xv[0. 20) (3.4)].: >>> x = np. versus defined as a slice or transpose. np. 4]].a array([1].8. Release 1. dtype=[(’a’.reshape(-1.3].int8)]) >>> xv = x. 4)] Using a view to convert an array to a record array: >>> z = x. type=np..[4. dtype=np. Examples >>> x = np.mean(0) array([ 2. np.NumPy Reference.2.matrixlib. dtype=int8) Views share data: >>> x[0] = (9. 2)].int8).(3. 0:2] >>> y array([[1. (’length’.recarray) >>> z.view(dtype=np.int8). dtype=[(’a’. [4. line 1.int16)]) Traceback (most recent call last): File "<stdin>". 2). if some_dtype has a different number of bytes per entry than the previous dtype (for example. [3. dtype=int16) >>> print type(y) <class ’numpy. np.array([(1.array([(1.matrix’> Creating a view on a structured array so it can be used in calculations >>> x = np. (’b’. Array objects .1 of the memory.view(np.array([[1. np. fortran-ordering.2) >>> xv array([[1. 10) >>> z[0] (9.int16) >>> y = x[:. etc.view(dtype=[(’width’.6]]. >>> z = y. transposes.

shape. dtype=np.2.5.byteswap(inplace) Swap the bytes of the array elements Toggle between low-endian and big-endian data representation by returning a byteswapped array.0]*4) >>> print x [[1.byteswap(True) array([ 256. optional If True.5. np.9. 1. dtype=[(’width’. ’fac’]) >>> A.astype(int32) [[1 -.array([[1. [(4.byteswap() array([’ceg’. (’length’. ’<i2’)]) MaskedArray.3. ’<i2’). A) [’0x100’.3.compressed() Return all the non-masked data as a 1-D array. Returns output : MaskedArray A copy of self cast to input newtype. A) [’0x1’.int16)]) array([[(1.NumPy Reference. If inplace is True. Parameters inplace : bool. 8755]. 13090]. 256.int16) >>> map(hex.0 -.array([’ceg’.[4.9]]. The returned record shape matches self. Examples >>> A = np.[7. dtype=’|S3’) MaskedArray.8.7.ma.int16).1] [-.0 --] [7. 5)]]. this is a view to self.1 >>> z. swap bytes in-place. mask=[0] + [1. ’0x2233’] >>> A. Returns out : ndarray The byteswapped array.astype(newtype) Returns a copy of the MaskedArray cast to given newtype. ’fac’]. default is False. Masked arrays 261 .0]] >>> print x. (’length’.array([1. ’0x3322’] Arrays of strings are not swapped >>> A = np.8.0 -. Returns data : ndarray 1.5 --] [7 -. dtype=int16) >>> map(hex. ’0x100’.3] [-.9]] MaskedArray.1].6].view(dtype=[(’width’. Release 1. 2)]. np. ’0x1’. optionally swapped in-place. Examples >>> x = np.

1]. Parameters fill_value : scalar.filled()) <type ’numpy.2. Returns filled_array : ndarray A copy of self with invalid entries replaced by fill_value (be it the function argument or the attribute of self. [999999.1 A new ndarray holding the non-masked data is returned.0. mask=[[0. optional The value to use for invalid entries (None by default). fill_value=-999) >>> x. 4]]) MaskedArray. Array objects . Warning: This function is not implemented yet. If None.4. filled returns a matrix: >>> x = np. Notes The result is not a MaskedArray! Examples >>> x = np.ma. mask=[0]*2 + [1]*3) >>> x.ma.tofile(fid.5].toflex() Transforms a masked array into a flexible-type array.ndarray’> MaskedArray. 999999]. [3.1].0. 0]]) >>> x.NumPy Reference. [1. sep=’‘. the fill_value attribute of the array is used instead.arange(5).filled(fill_value=None) Return a copy of self. 2].array(np.matrix([[1. -999. Notes The result is not a MaskedArray! Examples >>> x = np.array(np.compressed() array([0. MaskedArray.ma. Raises NotImplementedError When tofile is called. mask=[0. 4]]). with masked values filled with a given value.8. 1]) >>> type(x.filled() matrix([[ 1.ndarray’> Subclassing is preserved. Release 1. format=’%s’) Save a masked array to a file in binary format. 4. 262 Chapter 1.filled() array([1. This means that if the data part of the masked array is a matrix.3.array([1.compressed()) <type ’numpy.1. -999]) >>> type(x. 2.

8.) will be lost.6]. False) (6.3] [-. [-999. Data items are converted to the nearest compatible Python type.0]*4) >>> print x [[1 -. None]. Examples >>> x = np. Examples >>> x = np. Parameters None Returns record : ndarray A new flexible-type ndarray with two fields: the first element containing a value.shape. [7. True) (5.NumPy Reference. The returned record shape matches self. Returns result : list The Python list representation of the masked array. True) (3. Default is None.tolist(fill_value=None) Return the data portion of the masked array as a hierarchical Python list.tolist(-999) [[1.[7.tolist() [[1. 3].9]] >>> print x. 3]. the corresponding entries in the output list will be None.5 --] [7 -. Release 1. -999. The flexible type array that is returned will have two fields: 1. 5. [None.3].array([[1.. False) (2. Masked arrays 263 . optional The value to use for invalid entries.ma.. False)]] MaskedArray. None. 9]] MaskedArray. mask=[0] + [1.3]. -999.1 The flexible type array that is returned will have two fields: •the _data field stores the _data part of the array.2.9]]. Masked values are converted to fill_value. 5.6]. 9]] >>> x. the second element containing the corresponding mask boolean. •the _mask field stores the _mask part of the array. None.8. If fill_value is None. . False) (8. Notes A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value.5.array([[1. True)] [(7. [4.5.ma.7. Parameters fill_value : scalar.torecords() Transforms a masked array into a flexible-type array.2. [7. -999]. False)] [(4.8. True) (9. mask=[0] + [1.[4. [7.toflex() [[(1.9]].0]*4) >>> x.

tostring. optional Order of the data item in the copy.2.’F’. •the _mask field stores the _mask part of the array. tofile Notes As for ndarray. False) (2.9]]. • None – Same as ‘A’.tostring(fill_value=None. False)] [(4..9]] >>> print x.) will be lost.5. MaskedArray. . Default is ‘C’. 264 Chapter 1.’A’}. Parameters None Returns record : ndarray A new flexible-type ndarray with two fields: the first element containing a value. True)] [(7. tolist. dtype.array([[1. will be lost.8. the second element containing the corresponding mask boolean. Notes A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value.toflex() [[(1. etc.[7. • ‘F’ – Fortran order (column major). False)]] MaskedArray.1 •the _data field stores the _data part of the array. Array objects .NumPy Reference..5 --] [7 -. Deafult is None.fill_value is used. Examples >>> x = np.tostring. See Also: ndarray.ma. current order of array. in which case order : {‘C’. The array is filled with a fill value before the string conversion. False) (8.3]. optional Value used to fill in the masked values. • ‘C’ – C order (row major).3] [-. True) (9. False) (6. The returned record shape matches self.0]*4) >>> print x [[1 -. information about the shape. Release 1. order=’C’) Return the array data as a string containing the raw bytes in the array.8.6].. mask=[0] + [1. • ‘A’ – Any. True) (5. but also about fill_value. True) (3.shape.[4. Parameters fill_value : scalar.

2. flat A 1-D flat iterator over the array. mask=[[0.8. refcheck. MaskedArray. Returns a view of the array with axes transposed.T Return a copy of the array collapsed into one dimension. The default is ‘C’. 4]) >>> a. 2].ravel() Returns a 1D version of self. ‘F’.array([[1.2].flatten(’F’) array([1. 3.flatten() array([1.tostring() ’\x01\x00\x00\x00?B\x0f\x00?B\x0f\x00\x04\x00\x00\x00’ Shape manipulation For reshape. 2. resize. 4]) MaskedArray. axis2) MaskedArray.7. See Also: ravel Return a flattened array.4]]) >>> a.ravel() MaskedArray. 1]. and transpose. [3. ‘A’}. Give a new shape to the array without changing its data. or preserve the C/Fortran ordering from a. flattened to one dimension. 0]]) >>> x.ma. the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple. as a view.) (or 265 .product(self. Fortran (column-major) order. 3.resize(newshape[. [3. Examples >>> a = np. Remove single-dimensional entries from the shape of a.transpose(*axes) MaskedArray. order]) MaskedArray.NumPy Reference.flatten([order]) MaskedArray.size. Returns MaskedArray Output view is of shape (np. as a view. Returns a 1D version of self.)). 4]]). 1. optional Whether to flatten in C (row-major). Parameters order : {‘C’. Masked arrays (self.reshape(*s.1 Examples >>> x = np.squeeze([axis]) MaskedArray.array([[1.swapaxes(axis1. Return a view of the array with axis1 and axis2 interchanged. **kwargs) MaskedArray.ma. [1. MaskedArray.flatten(order=’C’) Return a copy of the array collapsed into one dimension. Release 1.shape). Returns y : ndarray A copy of the input array.array(np.

[7. to modify the shape in place.0. If an integer is supplied.shape = s Examples >>> x = np.7 -. ‘F’}. a ValueError is raised.reshape((4.8.2].5 --] [7 -.9]] >>> print x. Returns reshaped_array : array A new view on the array. See Also: reshape Equivalent function in the masked array module.4]].ma.[4.NumPy Reference.ndarray.reshape Equivalent function in the NumPy module. order : {‘C’. Notes The reshaping operation cannot guarantee that a copy will not be made.9] MaskedArray. then the result will be a 1-D array of that length. Array objects .5.reshape(*s.ravel() [1 -. Parameters shape : int or tuple of ints The new shape should be compatible with the original shape.6].0.8. but with a new shape.9]].3].3] [-.array([[1.reshape Equivalent method on ndarray object. optional Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order.[3. mask=[1. numpy.3 -.1]) >>> print x [[-.2.1 Examples >>> x = np.1)) >>> print x [[--] [2] [3] [--]] 266 Chapter 1.array([[1.0]*4) >>> print x [[1 -.2] [3 --]] >>> x = x. if this is not possible.5 -. Returns a masked array containing the same data. mask=[0] + [1. The result is a view on the original array. **kwargs) Give a new shape to the array without changing its data. use a.ma. Release 1. numpy.

shape = (i[n-1]. For an n-D array. with axes suitably permuted. this has no effect.T Array property returning the array transposed. except raise a ValueError exception. axis2) Return a view of the array with axis1 and axis2 interchanged.squeeze(axis=None) Remove single-dimensional entries from the shape of a. A masked array does not own its data and therefore cannot safely be resized in place. (To change between column and row vectors.swapaxes(axis1.ma. If axes are not provided and a. . Release 1.1 MaskedArray.transpose(*axes) Returns a view of the array with axes transposed. refcheck=True.resize function instead. tuple of ints. See Also: numpy. See Also: numpy...transpose(). first cast the 1-D array into a matrix object. This method is difficult to implement safely and may be deprecated in future releases of NumPy.squeeze for full documentation. i[0]). i[n-2].swapaxes for full documentation. or n ints • None or no argument: reverses the order of the axes. Use the numpy. Refer to numpy. i[1].transpose()‘s j-th axis. • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a.shape = (i[0]... order=False) Warning: This method does nothing. Masked arrays 267 .NumPy Reference. MaskedArray. then a. • 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. i[n-2].7.) For a 2-D array. if axes are given. their order indicates how the axes are permuted (see Examples). See Also: ndarray. i[1]. Refer to numpy.squeeze equivalent function MaskedArray. For a 1-D array. Examples 1. .swapaxes equivalent function MaskedArray.8.resize(newshape. this is the usual matrix transpose. i[n-1]). Parameters axes : None.

If axis is None. optional Value used to fill in the masked values. 4]]) >>> a array([[1. fill_value.. Parameters axis : {None.item(*args) MaskedArray. array}. out]) MaskedArray. 3]. Return an ndarray of indices that sort the array along the specified axis. [3. mode]) MaskedArray. sorter]) MaskedArray. it defaults to None. Use an index array to construct a new array from a set of choices.argmax([axis.NumPy Reference. the index is into the flattened array. Array objects . values[. Return a where condition is True._data) is used instead. 4]]) MaskedArray.choose(choices[.array([[1. order. Sort the array.T Item selection and manipulation For array methods that take an axis keyword. axis.transpose(1. Release 1. Return specified diagonals..compress(condition[.]) MaskedArray. integer} If None. out]) MaskedArray. Fill the array with a scalar value. [2.repeat(repeats[. 4]]) >>> a. Copy an element of an array to a standard Python scalar and return it.take(indices[.argmin([axis. kind.nonzero() MaskedArray. axis]) MaskedArray. MaskedArray.. Repeat elements of an array. out]) MaskedArray. [2. 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.put(indices. out=None) Returns array of indices of the maximum values along the given axis.transpose() array([[1. Masked values are treated as if they had the value fill_value. out. out. 0)) array([[1. side. 3]. 4]]) >>> a. [2.argmax(axis=None. the output of maxi- out : {None. 2]. mum_fill_value(self. fill_value=None. mode]) MaskedArray. then the array is treated as a 1-D array. Return array of indices to the minimum values along the given axis. 4]]) >>> a.8.transpose((1.sort([axis. 0) array([[1. 2]. 3]. axis1.searchsorted(v[. otherwise along the specified axis fill_value : {var}. 268 Chapter 1. order. . fill_value. mode]) Returns array of indices of the maximum values along the given axis.fill(value) MaskedArray.argsort([axis.diagonal([offset. [3. Set storage-indexed locations to corresponding values. Any other value for axis represents the dimension along which the operation should proceed. Return the indices of unmasked elements that are not zero. If None.1 >>> a = np. axis. kind. Find indices where elements of v should be inserted in a to maintain order.. in-place MaskedArray. axis2]) MaskedArray.]) MaskedArray.

_data) is used instead. returns a new ndarray of indices to the minimum values along the given axis. otherwise along the specified axis fill_value : {var}.ma.0. Masked values are filled beforehand to fill_value.shape = (2. Examples >>> x = np.argsort(axis=None. fill_value=-1) [0 0] >>> print x. The default is -1 (last axis). Its type is preserved and it must be of the right shape to hold the output. 1]) >>> a. 2]) MaskedArray.argmax() 5 >>> a. fill_value=None) Return an ndarray of indices that sort the array along the specified axis. mum_fill_value(self.argmax(0) array([1. Otherwise. order=None.--] [2 3]] >>> print x.1 Returns index_array : {integer_array} Examples >>> a = np. the flattened array is used. integer} If None.argmax(1) array([2. If None. Masked arrays 269 . fill_value=None.argmin(axis=None. kind=’quicksort’.2) >>> print x [[-. Release 1. array}. returns a scalar of index to the minimum values along the given axis. optional Value used to fill in the masked values.8. If None.3) >>> a.0]) >>> x. the output of mini- out : {None. 1. Returns {ndarray.arange(6).7. optional Array into which the result can be placed.argmin(axis=0. Parameters axis : int.NumPy Reference. fill_value=9) [1 1] MaskedArray. scalar} If multi-dimension input.argmin(axis=0. out=None) Return array of indices to the minimum values along the given axis. mask=[1.array(arange(4).1. the index is into the flattened array. fill_value : var. Parameters axis : {None.reshape(2. optional Axis along which to sort. optional 1.

sort Inplace sort.choose for full documentation. In other words. ndarray. Release 1. See Also: sort Describes sorting algorithms used. etc. 270 Chapter 1.NumPy Reference.8.array([3. mode=’raise’) Use an index array to construct a new array from a set of choices. Returns index_array : ndarray. int Array of indices that sort a along the specified axis. 2]) MaskedArray. fill_value = 999999) >>> a. mask=[False. Parameters condition : var Boolean 1-d array selecting which entries to return.choose equivalent function MaskedArray. True]) >>> a masked_array(data = [3 2 --]. Notes See sort for notes on the different sorting algorithms. Not all fields need be specified. 0.2. If condition is a MaskedArray.1 Value used to fill the array before sorting. mask = [False False True]. ‘heapsort’}.1]. Refer to numpy. Array objects . out=None) Return a where condition is True. False.argsort() array([1. missing values are considered as False. lexsort Indirect stable sort with multiple keys. this argument specifies which fields to compare first. Examples >>> a = np.ma. The default is the fill_value attribute of the input array. optional When a is an array with fields defined. out=None. second. axis=None. ‘mergesort’. optional Sorting algorithm.choose(choices. See Also: numpy. order : list. kind : {‘quicksort’.compress(condition. If len(condition) is less than the size of a along the axis. then output is truncated to length of condition array. a[index_array] yields a sorted a.

diagonal for full documentation.compress([1.9]]. 1]. See Also: numpy.5 --] [7 -. mask = [False False]. axis1=0.8.array([[1.[7. 0. Refer to numpy. optional Alternative output array in which to place the result. int}.--] [7 9]].fill(value) Fill the array with a scalar value.1 axis : {None. out : {None. Returns result : MaskedArray A MaskedArray object. 0.0]*4) >>> print x [[1 -. 1]) masked_array(data = [1 3]. Release 1. ndarray}. fill_value=999999) MaskedArray.8. axis2=1) Return specified diagonals. mask=[0] + [1.compress([1. It must have the same shape as the expected output but the type will be cast if necessary.diagonal equivalent function MaskedArray.3] [-. The output of compress has a mask. Parameters value : scalar All elements of a will be assigned this value.9]] >>> x.5. axis=1) masked_array(data = [[1 3] [-. 1. Masked arrays 271 . Notes Please note the difference with compressed ! compressed does not. mask = [[False False] [ True True] [False False]].3].7.diagonal(offset=0.NumPy Reference. fill_value=999999) >>> x.6].2. optional Axis along which the operation must be performed.[4.ma. the output of Examples >>> x = np.

5.array([1. Array objects . [2. Examples >>> x = np. Release 1.item((0. 3]]) >>> x. Void arrays return a buffer object for item().fill(0) >>> a array([0.1 Examples >>> a = np.item((2. Returns a tuple of arrays. 3)) >>> x array([[3. This can be useful for speeding up access to elements of the array and doing arithmetic on elements of the array using Python’s optimized math. specifying which element to copy and return. item() returns a scalar array object because there is no available Python scalar that would not lose information. 2]) >>> a. item is very similar to a[args]. instead of an array scalar. unless fields are defined. in which case a tuple is returned.]) MaskedArray.8.random. [8.item(7) 5 >>> x.empty(2) >>> a. except that the argument is interpreted as an nd-index into the array. 2)) 3 MaskedArray. 3]. The corresponding non-zero values can be obtained with: 272 Chapter 1. one for each dimension. 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. 1. containing the indices of the non-zero elements in that dimension.NumPy Reference.item(3) 2 >>> x.fill(1) >>> a array([ 1. 1. a standard Python scalar is returned. size=(3. 0]) >>> a = np. 1)) 1 >>> x.randint(9. except. 7]. 8.size == 1).nonzero() Return the indices of unmasked elements that are not zero. Parameters *args : Arguments (variable number and type) • none: in this case. the method only works for arrays with one element (a. • int_type: this argument is interpreted as a flat index into the array. • tuple of int_types: functions as does a single int_type argument.item(*args) Copy an element of an array to a standard Python scalar and return it.. which element is copied into a standard Python scalar object and returned.

Masked arrays 273 . mask = [[False False False] [False True False] [False False False]].8. flatnonzero Return indices that are non-zero in the flattened version of the input array.nonzero() (array([0.nonzero() (array([0.0 -.nonzero()] To group the indices by element.eye(3)) >>> x masked_array(data = [[ 1. fill_value=1e+20) >>> x. rather than dimension. with a row for each non-zero element. 2])) 1.ma as ma >>> x = ma. 1.1 a[a. array([0.0]]. 0. 0. 1.nonzero()) The result of this is always a 2d array.masked >>> x masked_array(data = [[1. 1] = ma. 2]). Parameters None Returns tuple_of_arrays : tuple Indices of elements that are non-zero.array(np. 2])) Masked elements are ignored.0. 1.0] [0.0 0.0 0. ndarray.] [ 0.0 1.NumPy Reference. 1. Examples >>> import numpy.0] [0. Release 1. mask = False.nonzero Function operating on ndarrays. fill_value=1e+20) >>> x. count_nonzero Counts the number of non-zero elements in the input array. 0. array([0.7.0 0. 0.]]. use instead: np.] [ 0.nonzero Equivalent ndarray method. 2]).transpose(a. See Also: numpy. >>> x[1.

Sets self. mode=’raise’) Set storage-indexed locations to corresponding values. mask = False. ‘wrap’. 2.6]. ‘raise’ : raise an error.30]) >>> print x [[10 -.9]]. Examples >>> x = np.transpose(x.3].put([0. ma._data copy at target indices. values.8. Notes values can be a scalar or length 1 array.8. where a condition is True. 0. mask=[0] + [1. fill_value=999999) >>> ma. If values has some masked values. optional Specifies how out-of-bounds indices will behave.20. 2.array([[1.3].8]. 1. array([0. 1.9]]) >>> a > 3 masked_array(data = [[False False False] [ True True True] [ True True True]].array([[1. ‘clip’ : clip to the range. values : array_like Values to place in self.5 --] [7 -. If values is shorter than indices then it will repeat. >>> a = ma. the condition a > 3 is a boolean array and since False is interpreted as 0.8.6]. Array objects . Release 1.nonzero(a > 3) (array([1. array([0. 0]. 2]).nonzero()) array([[0.9]] >>> x.nonzero() (array([1. 2])) The nonzero method of the condition array can also be called. Given an array a.2. 2. 2. 1.[10. interpreted as integers. 1.2. Parameters indices : 1-D array_like Target indices. ‘clip’}.3] [-.[4. 1._data.4. 1. [2. 1. >>> np. mode : {‘raise’. else the corresponding values are unmasked.1 Indices can also be grouped by element. >>> (a > 3).3] 274 Chapter 1. 0.ma.nonzero(a > 3) yields the indices of the a where the condition is true.NumPy Reference.5. ‘wrap’ : wrap around.[7.5.put(indices. 1. 2]]) A common use for nonzero is to find the indices of an array.[7. the initial mask is updated in consequence. 2. 2]).0]*4) >>> print x [[1 -.[4.flat[n] = values[n] for each n in indices. 2. 2])) MaskedArray.

in-place Parameters a : array_like Array to be sorted.20 --] [7 -. optional Sorting algorithm. ‘mergesort’. Masked arrays 275 . The default is -1.30]] >>> x. kind=’quicksort’. optional Axis along which to sort. False}. kind : {‘quicksort’. For full documentation. This list does not need to include all of the fields.repeat equivalent function MaskedArray. ‘heapsort’}. side=’left’.7. which sorts along the last axis. optional When a is a structured array.8. fill_value=None) Sort the array.1 [-. fill_value : {var}. If None.repeat for full documentation. second.3] [-. Release 1. it supersedes endwith.NumPy Reference. sorter=None) Find indices where elements of v should be inserted in a to maintain order. Default is ‘quicksort’. See Also: numpy.30]] MaskedArray.searchsorted equivalent function MaskedArray. axis : int.repeat(repeats. optional Whether missing values (if any) should be forced in the upper indices (at the end of the array) (True) or lower indices (at the beginning).sort(axis=-1. endwith : {True. and so on. order : list.searchsorted(v.put(4.999) >>> print x [[10 -. Returns sorted_array : ndarray 1. If fill_value is not None. axis=None) Repeat elements of an array. order=None. Refer to numpy.999 --] [7 -. this argument specifies which fields to compare first. the array is flattened before sorting.searchsorted See Also: numpy. see numpy. optional Value used internally for the masked values. endwith=True.

Array objects . mode=’raise’) Pickling and copy MaskedArray.dump(file) MaskedArray.sort Method to sort an array in-place. lexsort Indirect stable sort on multiple keys. See Also: ndarray. ‘C’ otherwise. Examples >>> a = ma. ‘F’ means F-order.3 5] MaskedArray.array([1. Parameters order : {‘C’.take(indices. fill_value=3) >>> print a [1 -. Notes See sort for notes on the different sorting algorithms. 4. 1. 0.-. 2.--] >>> >>> >>> >>> [-- a = ma.copy([order]) MaskedArray. 3]. 2.mask=[0. out=None. Returns the pickle of the array as a string.array([1.1 Array of the same type and shape as a. ‘F’. 1. 4.copy(order=’C’) Return a copy of the array. ‘A’ means ‘F’ if a is Fortran contiguous. ‘K’}.8.1 3 5] >>> a = ma. ‘K’ means match the layout of a as 276 Chapter 1.sort() >>> print a [1 3 5 -. 3]. Release 1. optional Controls the memory layout of the copy.mask=[0. 5. 0. 1. 0]) >>> # Default >>> a.array([1. 3]. 0]) # Put missing values in the front a. axis=None. ‘A’.sort(endwith=False. argsort Indirect sort. Dump a pickle of the array to the specified file. 5. 1. ‘C’ means C-order. 1.sort(endwith=False) print a -. 1. MaskedArray.mask=[0.dumps() Return a copy of the array. 0]) >>> # fill_value takes over endwith >>> a. 4. searchsorted Find elements in a sorted array. 2. 5.NumPy Reference. 0.

dtype.loads or numpy. fill_value]) 1.conjugate() MaskedArray.conj() MaskedArray.2. 6]]) >>> y.7.all([axis. but have different default values for their order= arguments. Return an array whose values are limited to [a_min.load. Release 1.cumprod([axis. Returns the average of the array elements. 2. Return the cumulative sum of the elements along the given axis. Return the product of the array elements over the given axis. 0.ptp([axis.min([axis. dtype.copyto Examples >>> x = np. out]) MaskedArray. 5.product([axis. Return the cumulative product of the elements along the given axis. Masked arrays Check if all of the elements of a are true. Compute the anomalies (deviations from the arithmetic mean) along the given ax Check if any of the elements of a are true. out]) MaskedArray.minimum) along the the given dimension (i. dtype]) MaskedArray. Parameters None Calculations MaskedArray.copy() >>> x.cumsum([axis. numpy. 0].copy are very similar. fill_value]) MaskedArray. Return the complex conjugate.anom([axis. Return the product of the array elements over the given axis. Continued on next pa 277 .mean([axis. 0. out]) MaskedArray. order=’F’) >>> y = x. fill_value]) MaskedArray.) See Also: numpy. (Note that this function and :func:numpy. Complex-conjugate all elements.clip(a_min. out. [0.dumps() Returns the pickle of the array as a string. 0]]) >>> y array([[1.loads will convert the string back to an array.copy.array([[1. Return the maximum along a given axis. The array can be read back with pickle. out]) MaskedArray.1 closely as possible.dump(file) Dump a pickle of the array to the specified file.load or numpy.e. dtype. Return the minimum along a given axis. a_max]. a_max[. out]) MaskedArray. out. out. MaskedArray. Parameters file : str A string naming the dump file. pickle.3].8. out]) MaskedArray.5.[4.fill(0) >>> x array([[0. out]) MaskedArray. element-wise. Return (maximum .flags[’C_CONTIGUOUS’] True MaskedArray. [4.prod([axis.NumPy Reference.any([axis. dtype. out]) MaskedArray.6]].max([axis. 3]. dtype.

Performs a logical_and over the given axis and returns the result. integer} Axis to perform the operation over.var([axis. for arrays of float types it is the same as the array type.anom(axis=None.1 Table 1. out.. with the same shape as the input and where the arithmetic mean is computed along the given axis. Parameters axis : {None. 278 Chapter 1.array([1. Release 1.8.masked) True MaskedArray.NumPy Reference. See Also: mean Compute the mean of the array. MaskedArray. ddof]) Compute the variance along the specified axis. Parameters axis : int.ma. Returns an array of anomalies. dtype.array([1.all(axis=None. If None.sum([axis.ma. mask=True) >>> (a. dtype=None) Compute the anomalies (deviations from the arithmetic mean) along the given axis. optional Type to use in computing the variance. Its type is preserved and it must be of the right shape to hold the output. . axis1. ddof]) Compute the standard deviation along the specified axis.2. dtype. optional Array into which the result can be placed. out=None) Check if all of the elements of a are true. axis2. See Also: all equivalent function Examples >>> np. perform over flattened array. Array objects . Masked values are considered as True during computation.std([axis.. out]) Return the sum of the array elements over the given axis. out. For arrays of integer type the default is float32. MaskedArray.3].]) Return the sum along diagonals of the array. out]) Return a with each element rounded to the given number of decimals. 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.all() is np.2. dtype.66 – continued from previous page MaskedArray. optional Axis over which the anomalies are taken. MaskedArray. then the output is masked.trace([offset.3]).all() True >>> a = np.round([decimals. array}. The default is to use the mean of the flattened array as reference.ma. For convenience. dtype : dtype. out : {None. MaskedArray. MaskedArray.

Refer to numpy.]. a_max. array}. Performs a logical_or over the given axis and returns the result.conjugate equivalent function MaskedArray.conjugate equivalent function 1.conjugate for full documentation.clip for full documentation.clip equivalent function MaskedArray.7. Masked arrays 279 . Refer to numpy. Parameters axis : {None. perform over flattened array and return a scalar.1 Examples >>> a = np. If None.2.conjugate for full documentation.ma.8. out=None) Return an array whose values are limited to [a_min. Refer to numpy.any(axis=None. Release 1. a_max]. mask = False. Its type is preserved and it must be of the right shape to hold the output. See Also: numpy. Masked values are considered as False during computation. See Also: numpy.NumPy Reference. fill_value = 1e+20) 1.clip(a_min. 0.array([1. integer} Axis to perform the operation over. MaskedArray. See Also: numpy. out : {None.conj() Complex-conjugate all elements. See Also: any equivalent function MaskedArray. element-wise. out=None) Check if any of the elements of a are true.anom() masked_array(data = [-1.3]) >>> a. optional Array into which the result can be placed.conjugate() Return the complex conjugate.

MaskedArray. int}. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. optional Type of the returned array and of the accumulator in which the elements are summed. out : ndarray. dtype}. Parameters axis : {None. dtype=None. the dtype is the same as that of a. Masked values are set to 1 internally during the computation. If dtype is not specified. dtype}. their position is saved. optional Axis along which the sum is computed. Notes The mask is lost if out is not a valid MaskedArray ! Arithmetic is modular when using integer types. the default platform integer is used. Returns cumprod : ndarray A new array holding the result is returned unless out is specified. and the result will be masked at the same locations. optional Alternative output array in which to place the result. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer.NumPy Reference. -1. However. Otherwise. In that case. 280 Chapter 1. otherwise over the specified axis. Array objects . Parameters axis : {None. dtype : {None. unless a has an integer dtype with a precision less than that of the default platform integer. dtype : {None. and no error is raised on overflow. in which case it counts from the last to the first axis. Masked values are set to 0 internally during the computation.1 MaskedArray. dtype=None.cumprod(axis=None. The cumulative product is taken over the flattened array by default.cumsum(axis=None. and the result will be masked at the same locations. it defaults to the dtype of a. -1. out=None) Return the cumulative product of the elements along the given axis. optional Axis along which the product is computed. The default (axis = None) is to compute over the flattened array. otherwise over the specified axis. in which case a reference to out is returned. 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. The cumulative sum is calculated over the flattened array by default.8. out : ndarray. However. optional Determines the type of the returned array and of the accumulator where the elements are multiplied. Release 1. their position is saved. out=None) Return the cumulative sum of the elements along the given axis. then the default platform integer precision is used. int}. The default (axis = None) is to compute over the flattened array. axis may be negative.

dtype : dtype.7. axis : int. Masked arrays 281 . If out was specified.0.cumsum() [0 1 3 -. Examples >>> marr = np.1. out=None) Returns the average of the array elements.0. and no error is raised on overflow. If a is not an array. The average is taken over the flattened array by default. optional Alternative output array in which to place the result.-. Notes The mask is lost if out is not a valid MaskedArray ! Arithmetic is modular when using integer types.-.9 16 24 33] MaskedArray.max(axis=None.1 Returns cumsum : ndarray.0]) >>> print marr.0. dtype=None. By default. If None. otherwise over the specified axis.NumPy Reference. optional Axis along which to operate. A new array holding the result is returned unless out is specified. Release 1.1.arange(10).0.8. in which case a reference to out is returned. int}. Refer to numpy. See Also: maximum_fill_value Returns the maximum filling value for a given datatype. optional 1. a conversion is attempted. fill_value : {var}. optional Axis along which the means are computed. mask=[0.ma.0. The default is to compute the mean of the flattened array.array(np. Masked entries are ignored. fill_value=None) Return the maximum along a given axis. use the output of maxi- Returns amax : array_like New array holding the result. axis is None and the flattened input is used. optional Value used to fill in the masked values. out is returned.1. out=None. MaskedArray.mean(axis=None.mean for the full documentation. mum_fill_value(). Must be of the same shape and buffer length as the expected output. out : array_like. Parameters axis : {None. Parameters a : array_like Array containing numbers whose mean is desired.

Returns mean : ndarray. optional Alternative output array in which to place the result. fill_value : {var}. False. out : array_like. otherwise a reference to the output array is returned. numpy. numpy. Array objects .array([1. Examples >>> a = np. Must be of the same shape and buffer length as the expected output. 282 Chapter 1. mask = [False False True]. see dtype parameter above If out=None. If None. out is returned. See Also: numpy. inputs it is the same as the input dtype.mean Equivalent function. Release 1.ma. optional Axis along which to operate. the default is float64. True]) >>> a masked_array(data = [1 2 --].min(axis=None. 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.8. out : ndarray. axis is None and the flattened input is used.mean() 1.ma. If out was specified.1 Type to use in computing the mean.average Weighted average. Parameters axis : {None.3]. fill_value=None) Return the minimum along a given axis. minimum_fill_value. int}. By default.5 MaskedArray.ma. out=None.2.NumPy Reference. for floating point. use the output of Returns amin : array_like New array holding the result. mask=[False. optional Value used to fill in the masked values. fill_value = 999999) >>> a. For integer inputs. See Also: minimum_fill_value Returns the minimum filling value for a given datatype.mean Equivalent function on non-masked arrays. returns a new array containing the mean values.

array}... See Also: prod equivalent function Notes Arithmetic is modular when using integer types.NumPy Reference. Returns a reference to the specified output array if specified. scalar}. int}. dtype=np.2.]. Masked arrays 283 .0 >>> np. then the product is over all the array elements. 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. the dtype is the same as that of a.2.. dtype=None. Returns product_along_axis : {array.2. Masked elements are set to 1 internally for computation. and no error is raised on overflow. Examples >>> np. dtype=None. out : {None. axis=1) array([ 2. dtype}.2.]) MaskedArray. out=None) Return the product of the array elements over the given axis.int32) 2 >>> np. If None is used. Otherwise.. 12. optional Alternative output array in which to place the result.]]. optional Axis over which the product is taken.prod([1.8.1 MaskedArray.4. out=None) Return the product of the array elements over the given axis.]. dtype}. see dtype parameter above.. Parameters axis : {None.4. then the product is over all the array elements.prod([[1.. optional 1. If None is used.prod(axis=None.].]) 2.0 >>> np.[3. 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. dtype : {None.prod([1. dtype : {None.prod([[1..]]) 24. int}. Release 1.product(axis=None. optional Axis over which the product is taken. It must have the same shape as the expected output but the type will be cast if necessary.[3. Parameters axis : {None. Masked elements are set to 1 internally for computation.7. then the default platform integer precision is used.

2. Returns ptp : ndarray..]. See Also: prod equivalent function Notes Arithmetic is modular when using integer types. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. array_like}. int}.4. and no error is raised on overflow.e. Returns an array whose shape is the same as a with the specified axis removed. unless out was specified. in which case a reference to out is returned. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer.[3.. out=None) Return a with each element rounded to the given number of decimals.[3. fill_value : {var}..2. A new array holding the result. optional Value used to fill in the masked values. Examples >>> np. optional Axis along which to find the peaks. peak-to-peak value). optional Alternative output array in which to place the result. then the default platform integer precision is used. out=None. It must have the same shape as the expected output but the type will be cast if necessary. array}.]].2...4. Parameters axis : {None.0 >>> np.2. out : {None..]) 2. Release 1. MaskedArray.int32) 2 >>> np..round(decimals=0.1 Determines the type of the returned array and of the accumulator where the elements are multiplied. 284 Chapter 1.prod([[1.]]) 24. fill_value=None) Return (maximum . see dtype parameter above.prod([1. Returns a reference to the specified output array if specified.NumPy Reference. dtype=np. Returns product_along_axis : {array. optional Alternative output array in which to place the result. Array objects . out : {None. If None (default) the flattened array is used.prod([[1.].ptp(axis=None. 12.]. Returns a 0d array when a is 1d or axis=None.0 >>> np. the dtype is the same as that of a.minimum) along the the given dimension (i.]) MaskedArray. Otherwise.8. axis=1) array([ 2.prod([1. scalar}.

e.1 Refer to numpy. return a new array containing the standard deviation.around equivalent function MaskedArray. Parameters a : array_like Calculate the standard deviation of these values. dtype=None. the axes which are reduced are left in the result as dimensions with size one. optional Type to use in computing the standard deviation. keepdims : bool. otherwise return a reference to the output array. ddof=0 provides a maximum likelihood estimate 1. nanstd. optional Alternative output array in which to place the result. Release 1. ddof=0) Compute the standard deviation along the specified axis. For arrays of integer type the default is float64.. The standard deviation is computed for the flattened array by default.around for full documentation.mean())**2)). Returns the standard deviation. axis : int.ddof. ddof is specified. optional If this is set to True. nanmean. The default is to compute the standard deviation of the flattened array. optional Means Delta Degrees of Freedom.NumPy Reference. The average squared deviation is normally calculated as x. std = sqrt(mean(abs(x . Returns standard_deviation : ndarray.ddof is used instead. a measure of the spread of a distribution. the divisor N .8. With this option.doc. for arrays of float types it is the same as the array type. ddof : int. otherwise over the specified axis. the result will broadcast correctly against the original arr. ddof=1 provides an unbiased estimator of the variance of the infinite population. out : ndarray. where N represents the number of elements. By default ddof is zero. Masked arrays 285 . If out is None. optional Axis along which the standard deviation is computed. see dtype parameter above. See Also: numpy.7. of the array elements. In standard statistical practice.std(axis=None.sum() / N. i. where N = len(x). It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary.ufuncs Section “Output arguments” Notes The standard deviation is the square root of the average of the squared deviations from the mean.x. mean. nanvar numpy. If. See Also: var. The divisor used in calculations is N . however. dtype : dtype. out=None.

especially for float32 (see example below).512*512). the dtype is the same as that of a.std(a. Release 1. std() can be inaccurate: >>> a = np. int}. so even with ddof=1. Parameters axis : {None. axis=1) array([ 0. optional Determines the type of the returned array and of the accumulator where the elements are summed. If an output array is specified. dtype : {None. dtype=np.:] = 0. Note that. a reference to out is returned. 1.NumPy Reference. ndarray}.5. dtype=np. out=None) Return the sum of the array elements over the given axis. a scalar is returned.1 of the variance for normally distributed variables. out : {None. 0. or if axis is None. Masked elements are set to 0 internally. this can cause the results to be inaccurate. so that the result is always real and nonnegative.sum(axis=None.8. Otherwise. 4]]) >>> np.std(a. 2]. dtype=None. optional Alternative output array in which to place the result.45172946707416706 Computing the standard deviation in float64 is more accurate: >>> np.:] = 1. it will not be an unbiased estimate of the standard deviation per se.float32) >>> a[0. axis=0) array([ 1.float64) 0.]) >>> np. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer. with the specified axis removed. then the default platform integer precision is used.. [3.1180339887498949 >>> np. For floating-point input. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. -1. The default (axis = None) is to compute over the flattened array. std takes the absolute value before squaring. dtype}.std(a. Array objects .zeros((2. Depending on the input data.5]) In single precision. The standard deviation computed in this function is the square root of the estimated variance. Examples >>> a = np.std(a) 1. optional Axis along which the sum is computed.44999999925552653 MaskedArray.std(a) 0. Specifying a higheraccuracy accumulator using the dtype keyword can alleviate this issue. Returns sum_along_axis : MaskedArray or scalar An array with the same shape as self.array([[1.0 >>> a[1. the std is computed using the same precision the input has. If self is a 0-d array.1 >>> np. 286 Chapter 1. for complex numbers.

[4. otherwise over the specified axis.8. axis2=1.1 Examples >>> x = np. out=None) Return the sum along diagonals of the array. where N represents the number of elements.7.int64)[0]) <type ’numpy. out=None. Release 1.9]]. ddof : int. the result will broadcast correctly against the original arr. For arrays of integer type the default is float32. optional Axis along which the variance is computed. dtype=np. Masked arrays 287 . dtype=None. It must have the same shape as the expected output. axis : int.0]*4) >>> print x [[1 -. dtype=None. With this option. optional Type to use in computing the variance.var(axis=None. 1.int64’> MaskedArray.ma. If a is not an array. dtype : data-type.[7. Parameters a : array_like Array containing numbers whose variance is desired. but the type is cast if necessary.8.3]. the axes which are reduced are left in the result as dimensions with size one.sum() 25 >>> print x. ddof=0) Compute the variance along the specified axis.trace equivalent function MaskedArray.5. Refer to numpy.array([[1. optional Alternate output array in which to place the result.sum(axis=1) [4 5 16] >>> print x.sum(axis=0.trace for full documentation.trace(offset=0. keepdims : bool. axis1=0. The default is to compute the variance of the flattened array.2.6].ddof. out : ndarray. Returns the variance of the array elements. By default ddof is zero. for arrays of float types it is the same as the array type.5 --] [7 -. a measure of the spread of a distribution. The variance is computed for the flattened array by default. See Also: numpy.3] [-.NumPy Reference.sum(axis=0) [8 5 12] >>> print type(x.9]] >>> print x. a conversion is attempted. optional If this is set to True. mask=[0] + [1. optional “Delta Degrees of Freedom”: the divisor used in the calculation is N .

dtype=np.var(a) 1. See Also: std.ddof is used instead.array([[1. where N = len(x). the divisor N .8. ddof=1 provides an unbiased estimator of the variance of a hypothetical infinite population.var(a. however. Examples >>> a = np. a reference to the output array is returned.ufuncs Section “Output arguments” Notes The variance is the average of the squared deviations from the mean.55)**2)/2 0. For floating-point input. var() can be inaccurate: >>> a = np.float32) >>> a[0.4]]) >>> np.20250000000000001 Arithmetic and comparison operations Comparison operators: 288 Chapter 1. i.:] = 0. var = mean(abs(x x. this can cause the results to be inaccurate.[3. otherwise. Specifying a higher-accuracy accumulator using the dtype keyword can alleviate this issue. 1..var(a.20249999932997387 >>> ((1-0.]) >>> np. the absolute value is taken before squaring.sum() / N..0 >>> a[1.doc. nanvar numpy.var(a) 0. nanmean.2]. the variance is computed using the same precision the input has.1 Returns variance : ndarray. axis=0) array([ 1. Depending on the input data.float64) 0.25]) In single precision.zeros((2. Note that for complex numbers.1 >>> np. ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables.25 >>> np.25.NumPy Reference.:] = 1. mean. If.55)**2 + (0.512*512). Array objects .e. axis=1) array([ 0. Release 1. 0. dtype=np.mean())**2). especially for float32 (see example below). see dtype parameter above If out=None. returns a new array containing the variance. ddof is specified. The mean is normally calculated as x. In standard statistical practice. nanstd.var(a.1-0.20405951142311096 Computing the variance in float64 is more accurate: >>> np. so that the result is always real and nonnegative.

x.__mod__(y) <==> x%y x.1 MaskedArray. and return a new masked array. and return a new masked array. x.__nonzero__ x. Divide other into self.__rdivmod__(y) <==> divmod(y. Add other to self.__gt__(y) <==> x>y x.8. y) MaskedArray.__ge__(y) <==> x>=y MaskedArray.__nonzero__() <==> x != 0 Arithmetic: MaskedArray.__le__ MaskedArray. Multiply other by self. Subtract other to self.__truediv__(other) MaskedArray. Multiply other by self.__eq__(other) Check whether other equals self elementwise MaskedArray.__lt__(y) <==> x<y MaskedArray.__lt__ x.__abs__() <==> abs(x) MaskedArray.__rmul__(other) MaskedArray.__radd__(other) MaskedArray.__nonzero__() <==> x != 0 MaskedArray.__mod__ MaskedArray.__lt__ MaskedArray. Masked arrays Add other to self.__rtruediv__(other) MaskedArray. and return a new masked array.__ge__(y) <==> x>=y Check whether other equals self elementwise Check whether other doesn’t equal self elementwise MaskedArray.__rdiv__ MaskedArray. and return a new masked array. and return a new masked array.__eq__(other) MaskedArray.__floordiv__(other) MaskedArray.__le__ x.__rfloordiv__(other) MaskedArray.__ge__ MaskedArray. Divide other into self.__sub__(other) MaskedArray.7. and return a new masked array. Divide other into self.__mul__(other) MaskedArray.__gt__ x. masking the potential NaNs/Infs Continued on next page 289 .__ge__ x.__rsub__(other) MaskedArray.__rmod__(y) <==> y%x Raise self to the power other.__nonzero__ x. Divide other into self. Release 1. and return a new masked array.__rmod__ MaskedArray. and return a new masked array.__lt__(y) <==> x<y x.__ne__(other) Check whether other doesn’t equal self elementwise Truth value of an array (bool): MaskedArray. and return a new masked array.__gt__(y) <==> x>y MaskedArray.__divmod__(y) <==> divmod(x.__le__(y) <==> x<=y MaskedArray. and return a new masked array.__ne__(other) x.__gt__ MaskedArray. x) MaskedArray. Subtract other to self.__pow__(other) 1.NumPy Reference. and return a new masked array.__add__(other) MaskedArray.__rdiv__(y) <==> y/x Divide other into self.__div__(other) MaskedArray.__le__(y) <==> x<=y x.

__rtruediv__(other) Divide other into self.__ror__(y) <==> y|x x. and return a new masked array. and return a new masked array. y) 290 Chapter 1. Release 1.__ror__ MaskedArray.__mod__ x. MaskedArray. and return a new masked array.__rmod__(y) <==> y%x MaskedArray.__xor__(y) <==> x^y x. and return a new masked array.__rxor__ Table 1.__divmod__(y) <==> divmod(x.__add__(other) Add other to self.__abs__() <==> abs(x) MaskedArray.__rand__(y) <==> y&x x.__div__(other) Divide other into self.NumPy Reference. Array objects . and return a new masked array.__rshift__ MaskedArray. MaskedArray. MaskedArray.__rrshift__ MaskedArray. masking the potential NaNs/Infs x.__rmod__ x. MaskedArray.69 – continued from previous page Raise self to the power other.__rlshift__(y) <==> y<<x x. MaskedArray. and return a new masked array. MaskedArray.__sub__(other) Subtract other to self.__rxor__(y) <==> y^x MaskedArray. and return a new masked array. MaskedArray.__lshift__ MaskedArray.__or__ MaskedArray.__rdiv__(y) <==> y/x MaskedArray.__rand__ MaskedArray.__rshift__(y) <==> x>>y x.__floordiv__(other) Divide other into self.__and__ MaskedArray. and return a new masked array.__rlshift__ MaskedArray. MaskedArray. MaskedArray.__xor__ MaskedArray.__rpow__(other) MaskedArray.__mul__(other) Multiply other by self. and return a new masked array.__lshift__(y) <==> x<<y x.__radd__(other) Add other to self. MaskedArray. and return a new masked array.__or__(y) <==> x|y x.1 MaskedArray.__truediv__(other) Divide other into self.__rrshift__(y) <==> y>>x x.8. and return a new masked array.__and__(y) <==> x&y x.__rfloordiv__(other) Divide other into self.__rsub__(other) Subtract other to self. MaskedArray.__rdiv__ x.__mod__(y) <==> x%y MaskedArray.__rmul__(other) Multiply other by self.

__ilshift__(y) <==> x<<=y x. Release 1.__or__(y) <==> x|y MaskedArray. in place.__rlshift__ x.__rxor__(y) <==> y^x Arithmetic.__or__ x.__ilshift__ MaskedArray.__imod__ MaskedArray.__ifloordiv__(other) MaskedArray. masking the potential NaNs/Infs MaskedArray. Floor divide self by other in-place.__ior__(y) <==> x|=y x.__iand__ MaskedArray.NumPy Reference.__ixor__(y) <==> x^=y MaskedArray. Multiply self by other in-place.__rdivmod__(y) <==> divmod(y.__rlshift__(y) <==> y<<x MaskedArray.__rrshift__(y) <==> y>>x MaskedArray.8.__isub__(other) MaskedArray.__ior__ MaskedArray.__xor__(y) <==> x^y MaskedArray.__rxor__ x.__rrshift__ x.__rand__ x.__rpow__(other) Raise self to the power other.__iadd__(other) Add other to self in-place. Subtract other from self in-place.__and__(y) <==> x&y MaskedArray.__pow__(other) Raise self to the power other. MaskedArray.__rshift__ x. in-place: MaskedArray.__ror__(y) <==> y|x MaskedArray. x) MaskedArray.__ixor__ Add other to self in-place.__irshift__ MaskedArray.__ipow__(other) MaskedArray. masking the potential NaNs/Infs MaskedArray.__idiv__(other) MaskedArray.__lshift__ x.__iadd__(other) MaskedArray.__imul__(other) MaskedArray. Divide self by other in-place.__and__ x.__rand__(y) <==> y&x MaskedArray. x.__irshift__(y) <==> x>>=y x.__xor__ x. Masked arrays 291 .__ror__ x. x.__rshift__(y) <==> x>>y MaskedArray.__iand__(y) <==> x&=y x.__itruediv__(other) MaskedArray.__isub__(other) 1.7.1 MaskedArray.__imod__(y) <==> x%=y Raise self to the power other.__lshift__(y) <==> x<<y MaskedArray. True divide self by other in-place.

__ipow__(other) Raise self to the power other.__ior__ x. MaskedArray.__idiv__(other) Divide self by other in-place. Parameters None Examples >>> x = np. MaskedArray.__ilshift__ x. MaskedArray.__ifloordiv__(other) Floor divide self by other in-place. 3].ids() (166670640.__ixor__(y) <==> x^=y Representation MaskedArray. String representation.ids() MaskedArray. 2. in place.1 Subtract other from self in-place.__str__() MaskedArray. Array objects .__iand__(y) <==> x&=y MaskedArray.NumPy Reference.__irshift__ x. mask=[0. Release 1.array([1.__ilshift__(y) <==> x<<=y MaskedArray. 166659832) 292 Chapter 1.__repr__() MaskedArray. 1.__imod__(y) <==> x%=y MaskedArray.__imod__ x. MaskedArray.__imul__(other) Multiply self by other in-place.__itruediv__(other) True divide self by other in-place. MaskedArray. MaskedArray.__ixor__ x.__str__() String representation. Return the addresses of the data and mask areas.__iand__ x. 1]) >>> x.ma.ids() Return the addresses of the data and mask areas. Return a boolean indicating whether the data is contiguous.iscontiguous() Literal string representation. MaskedArray.__irshift__(y) <==> x>>=y MaskedArray.8.__ior__(y) <==> x|=y MaskedArray. MaskedArray. MaskedArray.__repr__() Literal string representation.

1.7.ma.flags C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False Special methods For standard library functions: MaskedArray.NumPy Reference.iscontiguous() True iscontiguous returns one of the flags of the masked array: >>> x. for pickling purposes. Restore the internal state of the masked array.__reduce__() Return a 3-tuple for pickling a MaskedArray.iscontiguous() Return a boolean indicating whether the data is contiguous. ‘F’. optional If order is ‘C’ (False) then the result is contiguous (default).1 If the array has no mask. 3]) >>> x. the address of nomask is returned.ids() (166691080. Masked arrays 293 . If order is ‘Any’ (None) then the result has fortran order only if the array already is in fortran order. Release 1. for pickling Return a 3-tuple for pickling a MaskedArray.__copy__([order ]) Return a copy of the array.ma. 3083169284L) MaskedArray. for pickling purposes.8.__setstate__(state) Return a copy of the array. 2. ‘A’}.__getstate__() Return the internal state of the masked array.__getstate__() MaskedArray.array([1.__deepcopy__(memo=None) MaskedArray. This address is typically not close to the data in memory: >>> x = np. 3]) >>> x. If order is ‘Fortran’ (True) then the result has fortran order. MaskedArray. 2. MaskedArray. Parameters order : {‘C’.__copy__([order]) MaskedArray. Return the internal state of the masked array. MaskedArray.__deepcopy__([memo]) MaskedArray.__reduce__() MaskedArray. Parameters None Examples >>> x = np.array([1.

hard_mask=None. mask=False. keep_mask=True.__setitem__(indx. Array objects .view(MaskedArray).__getitem__(indx) MaskedArray.__array__(. **options) Create a new masked array from scratch. If value is masked.__setitem__(i. value) x. 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. j) MaskedArray. mask.__setslice__(i.NumPy Reference.. Release 1. ndmin=0.__new__([data. y) <==> x[i]=y x. value) MaskedArray. Container customization: (see Indexing) MaskedArray.]) MaskedArray. y) <==> x[i]=y Set item described by index. shrink=True. j) <==> x[i:j] x.) MaskedArray. masks those locations. as a masked array. dtype. dtype=None.__getslice__(i.. MaskedArray. 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. j. Wraps the numpy array and sets the mask according to context.__delitem__(y) <==> del x[y] x.__array_wrap__(obj[.__new__(data=None. copy=False. value) MaskedArray.__getitem__(y) <==> x[y] x. static MaskedArray. Basic customization: MaskedArray.__getitem__(indx) x.__getslice__(i. Returns either a new reference to self if dtype is not given or a new array Special hook for ufuncs. state is typically the output of the __getstate__ output. fill_value=None.. MaskedArray. context=None) Special hook for ufuncs. value) <==> x[i:j]=value x. MaskedArray.__delitem__ 294 Chapter 1. subok=True.__contains__(y) <==> y in x MaskedArray.1 MaskedArray.__array_wrap__(obj. . copy otherwise..__contains__ x. Notes A masked array can also be created by taking a . MaskedArray.__delitem__ MaskedArray.__setstate__(state) Restore the internal state of the masked array. j.__setitem__(i. for pickling purposes.__setslice__(i.__len__() <==> len(x) MaskedArray.8.__array__(|dtype) → reference if type unchanged.__setitem__(indx.__getitem__(y) <==> x[y] Return the item described by i. context]) Create a new masked array from scratch.__len__() <==> len(x) MaskedArray.

The use of negative indices is not supported. soften_mask sets hardmask to False. Copy the mask and set the sharedmask flag to False. j) x. See Also: hardmask MaskedArray. Force the mask to hard. j) <==> x[i:j] Return the slice described by (i. If value is masked. harden_mask sets hardmask to True.soften_mask() Force the mask to soft. MaskedArray.7.__setslice__(i. Whether the mask is shared between masked arrays can be seen from the sharedmask property. copy]) MaskedArray.__delitem__(y) <==> del x[y] MaskedArray. Whether the mask of a masked array is hard or soft is determined by its hardmask property. Masked arrays 295 .harden_mask() MaskedArray. Whether the mask of a masked array is hard or soft is determined by its hardmask property. Reduce a mask to nomask when possible.__contains__(y) <==> y in x Specific methods Handling the mask The following methods can be used to access information about the mask or to manipulate the mask. 1. See Also: sharedmask MaskedArray.shrink_mask() Reduce a mask to nomask when possible. j. copy=False) Set the mask.__setmask__(mask. j).unshare_mask() MaskedArray.__getslice__(i. MaskedArray. A copy of the mask is only made if it was shared. j. value) x.harden_mask() Force the mask to hard. MaskedArray.__setslice__(i.__getslice__(i. MaskedArray.8.NumPy Reference. See Also: hardmask MaskedArray. value) <==> x[i:j]=value Set the slice (i. Force the mask to soft. MaskedArray.__setmask__(mask[. Release 1.__contains__ x.j) of a to value.unshare_mask() Copy the mask and set the sharedmask flag to False.shrink_mask() Set the mask. unshare_mask ensures the mask is not shared.1 x.soften_mask() MaskedArray. mask those locations.

Default is None.mask array([[False..get_fill_value() MaskedArray.set_fill_value([value]) Return the filling value of the masked array.ma. MaskedArray. 1]. 999999 999999 1e+20 (1e+20+0j) >>> x = np. Returns fill_value : scalar The filling value.].2 ]. fill_value=-np. Parameters value : scalar. dtype=bool) >>> x. 1. [3.get_fill_value() . [False. 4]]. False]].1 Parameters None Returns None Examples >>> x = np.float64. See Also: ma.. np..int32.8.ma.array([0. mask=[0]*4) >>> x.int64.get_fill_value() -inf MaskedArray. Examples >>> for dt in [np. 296 Chapter 1.mask False Handling the fill_value MaskedArray. np. dtype=dt). in which case a default based on the data type is used.get_fill_value() Return the filling value of the masked array.ma.array([0. Set the filling value of the masked array. Array objects ..shrink_mask() >>> x. np. optional The new filling value. np.inf) >>> x.set_fill_value(value=None) Set the filling value of the masked array. False].complex128]: . Release 1.array([[1.set_fill_value Equivalent function.NumPy Reference.

is returned.fill_value 1e+20 Counting the missing elements MaskedArray.7.inf) >>> x.arange(6). 1.1415926535897931 Reset to default: >>> x. 3)) >>> a[1.count([axis]) Count the non-masked elements of the array along the given axis. 1]) 1.NumPy Reference. See Also: count_masked Count masked elements in array or along a given axis.reshape((2. fill_value = 999999) >>> a. If axis is None.masked >>> a masked_array(data = [[0 1 2] [-. :] = ma. mask = [[False False False] [ True True True]]. fill_value=-np. When axis is not None.].--]]. MaskedArray. Returns result : int or ndarray If axis is None. an array with shape determined by the lengths of the remaining axes. >>> a.fill_value -inf >>> x.count(axis=0) array([1. 1.pi) >>> x. Masked arrays 297 . Examples >>> import numpy.ma as ma >>> a = ma.array([0. Parameters axis : int.fill_value 3.8.-.count() 3 When the axis keyword is specified an array of appropriate size is returned. an integer count is returned. optional Axis along which to count the non-masked elements. Release 1.ma. all non-masked elements are counted.set_fill_value(np.set_fill_value() >>> x.count(axis=None) Count the non-masked elements of the array along the given axis.1 Examples >>> x = np.

Character code: ?. dtype=None. ndmin=0. copy=False. count. subok=True.7. shape.dtype. optional Data type of the output. Construction: x = MaskedArray(data. . order=False. mask : sequence. copy=False. copy : bool.MaskType Numpy’s Boolean type.NumPy Reference.MaskedArray.]) ma. optional 298 Chapter 1.copy([order]) An array class with possibly masked values. If dtype is not None and different from data.masked_array ma. shrink=True) Parameters data : array_like Input data.ma.masked_array alias of MaskedArray numpy. dtype.ma. mask=False. dtype.count(axis=1) array([3. fill_value=None.frombuffer(buffer[. Array objects . **kwargs) ma.dtype) is used. fill_value=None. the type of the data argument (data. mask. An array class with possibly masked values. Release 1. keep_mask=True.. dtype : dtype. copy.array(data[. Masked values of True exclude the corresponding element from any computation. order..copy ma. ndmin=0) An array class with possibly masked values. copy Interpret a buffer as a 1-dimensional array. hard_mask=False. shrink=True. 0]) 1. keep_mask=True.7 Masked array operations Constants ma.ma. subok=True. invalid) data. Must be convertible to an array of booleans with the same shape as data. numpy. a copy is performed.MaskType alias of bool_ Creation From existing data ma. dtype=None. Construct an array by executing a function over each coordinate.fromfunction(function. offset]) ma. True indicates a masked (i. optional Mask.e. Alias: bool8 numpy. hard_mask=None. If dtype is None.1 >>> a.array(data. mask=nomask. Return a copy of the array.8.

copy() >>> x. optional Controls the memory layout of the copy. a default based on the data-type is used.NumPy Reference. Release 1. but have different default values for their order= arguments. 6]]) >>> y. ‘F’.copy are very similar. ‘K’ means match the layout of a as closely as possible. hard_mask : bool. optional Whether to combine mask with the mask of the input data. or to use a reference instead. ‘A’. [0. If None. 0.5. optional Value used to fill in the masked values when necessary.ma. ‘F’ means F-order. keep_mask : bool. shrink : bool. 0. optional Whether to return a subclass of MaskedArray if possible (True) or a plain MaskedArray.core. if any (True). order=’F’) >>> y = x. or to use only mask for the output (False).8. subok : bool. 3].2. 5. masked values cannot be unmasked. ‘A’ means ‘F’ if a is Fortran contiguous.copy(order=’C’) Return a copy of the array.) Examples >>> x = np. optional Minimum number of dimensions. Default is True.3].array([[1. Default is False. [4. Default is 0.fill(0) >>> x array([[0. 0]. Masked arrays 299 . ndmin : int.ma. Parameters order : {‘C’. 2. optional Whether to use a hard mask or not.1 Whether to copy the input data (True). 0]]) >>> y array([[1. numpy. optional Whether to force compression of an empty mask. Default is True.copy = <numpy. fill_value : scalar. ‘C’ otherwise. With a hard mask.7. Default is True. ‘C’ means C-order._frommethod instance at 0x2820290> copy a. ‘K’}.flags[’C_CONTIGUOUS’] True 1.6]]. (Note that this function and :func:numpy. Default is False.[4.

) tuple of ints Shape of the output array. (0. count=-1. dtype=float.ma. offset=0) = <numpy. shape.: >>> dt = np._convert2ma instance at 0x2820e18> Construct an array by executing a function over each coordinate. but will be interpreted correctly. optional Start reading the buffer from this offset. count : int. y. Examples >>> s = ’hello world’ >>> np.core. default: 0.1 numpy.ma. For example.frombuffer(buffer. Notes If the buffer has data that is not in machine byte-order. Parameters function : callable The function is called with N parameters. -1 means all data in the buffer.frombuffer(s. optional Data-type of the returned array. By default. y.g. Release 1. this should be specified as part of the data-type.8. shape : (N. ’r’. Array objects . 2). Returns fromfunction : any 300 Chapter 1. Each parameter represents the coordinates of the array varying along a specific axis. dtype : data-type. dtype=dt) The data of the resulting array will not be byteswapped. 1). dtype=’|S1’) numpy. offset : int. 0). e.dtype(int) >>> dt = dt. (1.NumPy Reference. then the parameters in turn be (0. count=5. **kwargs) = <numpy. optional Data-type of the coordinate arrays passed to function.fromfunction(function. if shape were (2. dtype=’S1’. optional Number of items to read. default: float. Parameters buffer : buffer_like An object that exposes the buffer interface.ma. where N is the rank of shape.newbyteorder(’>’) >>> np. ’d’]. 1). dtype : data-type._convert2ma instance at 0x2820dd0> Interpret a buffer as a 1-dimensional array.core. z) at coordinate (x. (1. z).ma. offset=6) array([’w’. The resulting array therefore has a value fn(x. dtype is float. 0). ’o’. which also determines the shape of the coordinate arrays passed to function.frombuffer(buf. ’l’.

j: i == j.copy are very similar. See Also: indices.) See Also: numpy.flags[’C_CONTIGUOUS’] True Ones and zeros 1. ‘K’}.[4. 2]. 4]]) MaskedArray. j: i + j. Examples >>> np. If function returns a scalar value.2. ‘K’ means match the layout of a as closely as possible. Therefore the shape of fromfunction is completely determined by function. (Note that this function and :func:numpy. (3. [False. dtype=bool) >>> np. meshgrid Notes Keywords other than dtype are passed to function. 0]]) >>> y array([[1. order=’F’) >>> y = x. True]]. numpy.3]. but have different default values for their order= arguments. 2. ‘C’ means C-order. 0.5.copyto Examples >>> x = np. [2. False]. ‘C’ otherwise. 3). (3. 2. optional Controls the memory layout of the copy.copy(order=’C’) Return a copy of the array. Parameters order : {‘C’.6]]. 5. True. False. 6]]) >>> y. ‘A’. 0. 3]. ‘F’.7.NumPy Reference. dtype=int) array([[ True.fill(0) >>> x array([[0.fromfunction(lambda i.fromfunction(lambda i. False. 3). 3. [1. [4. ‘F’ means F-order. ‘A’ means ‘F’ if a is Fortran contiguous. dtype=int) array([[0. Masked arrays 301 .array([[1. 0]. Release 1.copy() >>> x.8. the shape of fromfunction would match the shape parameter.1 The result of the call to function is passed back directly. 1. False]. 3]. [0. [False.copy.

order]) ma. order : {‘C’. order : {‘C’.zeros(shape[.NumPy Reference. [ 2.ma. Array objects . optional New in version 1. ‘F’ means F-order.1 ma. See Also: empty_like. 6. Overrides the memory layout of the result. order]) ma.ma. 19249760]]) #random #random numpy.6. dtype : data-type.0. subok]) ma. 2].ones(shape[.6. subok=True) = <numpy. 2]) array([[ -9. zeros. and may therefore be marginally faster. Empty masked array with all elements masked. dtype=None. ‘F’}. Parameters a : array_like The shape and data-type of a define these same attributes of the returned array. ‘A’. ‘C’ otherwise. Return a new array of given shape and type.empty(shape. order]) Return a new array of given shape and type. ‘A’ means ‘F’ if a is Fortran contiguous. 3. dtype. dtype]) ma. Overrides the data type of the result._convert2ma instance at 0x2820d88> Return a new array with the same shape and type as a given array.core.empty([2.empty_like(a[.8. optional New in version 1. -1067949133].74499359e+001.13182611e-314. Return a new array of given shape and type. dtype=float. ‘F’. order=’K’. [ 496041986. Parameters shape : int or tuple of int Shape of the empty array dtype : data-type. On the other hand. Return a new array with the same shape and type as a given array. without initializing entries. does not set the array values to zero. filled with ones. filled with zeros. dtype. or ‘K’}. ‘C’ means C-order. optional Desired output data-type. 302 Chapter 1. Empty masked array with the properties of an existing array.0. it requires the user to manually set all the values in the array.masked_all_like(arr) ma. dtype.core. order=’C’) = <numpy.ma.ma. unlike zeros. and should be used with caution. ones Notes empty. Examples >>> np.empty(shape[. optional Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory. ‘K’ means match the layout of a as closely as possible. order.06959433e-309]]) >>> np. without initializing entries. Release 1.masked_all(shape[.empty([2.empty_like(a. dtype. dtype=int) array([[-1073741821. numpy._convert2ma instance at 0x2820cf8> Return a new array of given shape and type.69583040e-309].

Returns a : MaskedArray A masked array with all data masked. -1073741821.8. 0.5.empty_like(a) array([[-1073741821. See Also: 1.7.1 subok : bool. -2.2.empty_like(a) array([[ -2.38791518e-305. 3]. Return an empty masked array of the given shape and dtype. ones Return a new array setting values to one. Returns out : ndarray Array of uninitialized (arbitrary) data with the same shape and type as a. Notes This function does not initialize the returned array. then the newly created array will use the sub-class type of ‘a’. 4. See Also: ones_like Return an array of ones with shape and type of input. 1.6..00000715e+000.NumPy Reference.17269252e-309]]) numpy. Masked arrays 303 . 3. otherwise it will be a base-class array.00000715e+000. 2. empty Return a new uninitialized array. Defaults to True.masked_all(shape.[4.. [4.5.]. zeros Return a new array setting values to zero..3].6]) # a is array-like >>> np.]]) >>> np.48219694e-323. to do that use zeros_like or ones_like instead. Release 1. It may be marginally faster than the functions that do set the array values. zeros_like Return an array of zeros with shape and type of input. If True. dtype : dtype. optional Data type of the output. #random [ 0. Parameters shape : tuple Shape of the required MaskedArray. optional.00000572e+000]..array([[1.ma. Examples >>> a = ([1. dtype=<type ‘float’>) Empty masked array with all elements masked. where all the data are masked.#random [ 4. -1073741821]]) >>> a = np. -2.

dtype=np.--] [-.dtype dtype(’int32’) numpy. 3)) masked_array(data = [[-. 3)) >>> a.int32) >>> a.ma as ma >>> arr = np.-.dtype dtype(’float64’) >>> a = ma.--] [-. mask = [[ True True True] [ True True True] [ True True True]].--] 304 Chapter 1. Raises AttributeError If arr doesn’t have a shape attribute (i.-. Release 1.masked_all_like(arr) Empty masked array with the properties of an existing array.masked_all((3.]]. 3). Return an empty masked array of the same shape and dtype as the array arr.masked_all_like(arr) masked_array(data = [[-. 0.-. dtype=np. Array objects . 0.. >>> a = ma..float32) >>> arr array([[ 0. where all the data are masked. Parameters arr : ndarray An array describing the shape and dtype of the required MaskedArray. not an ndarray) See Also: masked_all Empty masked array with all elements masked.NumPy Reference..].ma as ma >>> ma. 0. fill_value=1e+20) The dtype parameter defines the underlying data type.masked_all((3.. Examples >>> import numpy.-.masked_all((3. 0.e. dtype=float32) >>> ma. Examples >>> import numpy. Returns a : MaskedArray A masked array with all data masked.zeros((2.--]].1 masked_all_like Empty masked array modelled on an existing array.ma. [ 0. 3).8.

optional The desired data-type for the array..ma. Parameters shape : int or sequence of ints 1.ones(shape._convert2ma instance at 0x2820ef0> Return a new array of given shape and type. 1)) array([[ 1..ones(5) array([ 1. order=’C’) = <numpy. 1]) >>> np. optional Whether to store multidimensional data in C.g.1 [-.. See Also: zeros..]]) numpy.zeros(shape.ma. filled with zeros. dtype.dtype dtype(’float32’) >>> ma.or columnwise) order in memory.-. dtype=None. Release 1. 1. 1. [ 1.). 3) or 2.]]) >>> s = (2. 1.ones((5. (2. filled with ones. order=’C’) = <numpy.]) >>> np. ‘F’}. 1. dtype : data-type.core. 1. ones_like Examples >>> np.. [ 1. e.dtype dtype(’float32’) numpy. Default is numpy. and order. >>> arr.NumPy Reference.core.--]]. e. 1.ma.or Fortran-contiguous (row.2) >>> np.ma. mask = [[ True True True] [ True True True]].int) array([1. Masked arrays 305 .]. order : {‘C’.ones(s) array([[ 1. 1. fill_value=1e+20) The dtype of the masked array matches the dtype of arr.. 1.ones((2.masked_all_like(arr).float64. 1.g. Returns out : ndarray Array of ones with the given shape.. dtype=float.int8. Parameters shape : int or sequence of ints Shape of the new array.8._convert2ma instance at 0x2820f80> Return a new array of given shape and type..].7. dtype=np. numpy.

dtype=numpy. 0). empty_like Return an empty array with shape and type of input.]]) >>> np. (’y’. Default is numpy. 0. ones Return a new array setting values to one. 3) or 2. 0.or columnwise) order in memory. out]) Check if all of the elements of a are true.or Fortran-contiguous (row..].zeros(s) array([[ 0. 0. e. ’i4’). 0. empty Return a new uninitialized array. dtype. 0. ones_like Return an array of ones with shape and type of input.. optional The desired data-type for the array. 1)) array([[ 0. optional Whether to store multidimensional data in C.zeros((2.1 Shape of the new array. [ 0.2) >>> np. [ 0.g. ‘F’}. axis. Release 1. 0]) >>> np.g. dtype : data-type. (’y’. 0. Continued on next page 306 Chapter 1.).int8.zeros(5) array([ 0. ’<i4’). ’<i4’)]) Inspecting the array ma. Returns out : ndarray Array of zeros with the given shape.]]) >>> s = (2..zeros((2.zeros((5. Examples >>> np. and order. dtype=[(’x’.NumPy Reference. 0. See Also: zeros_like Return an array of zeros with shape and type of input. order : {‘C’. 0..]. ’i4’)]) # custom dtype array([(0. (2.. dtype=[(’x’..all(self[.]) >>> np. e. Array objects .float64. 0)].int) array([0. 0.. (0.. numpy.).8.

out=None) = <numpy.nonzero() Return the indices of unmasked elements that are not zero.all(self. out]) Check if any of the elements of a are true.count(a[.any(self[.core.ma. out : {None. out]) Check if any of the elements of a are true._frommethod instance at 0x2819e18> Check if all of the elements of a are true. Performs a logical_and over the given axis and returns the result.getmask(a) Return the mask of a masked array.array([1.7._frommethod instance at 0x2819fc8> Check if any of the elements of a are true. ma. ma.masked) True numpy. axis. Masked values are considered as False during computation. numpy. Its type is preserved and it must be of the right shape to hold the output.MaskedArray.NumPy Reference. mask=True) >>> (a.2. ma. axis=None.all() is np. Masked values are considered as True during computation. ma.core.MaskedArray.8.MaskedArray. axis]) Count the non-masked elements of the array along the given axis. ma. ma. Performs a logical_or over the given axis and returns the result.ma. out=None) = <numpy. ma.all() True >>> a = np. ma. See Also: all equivalent function Examples >>> np. Release 1. or full boolean array of False.MaskedArray.MaskedArray.ma.ma. integer} 1. Parameters axis : {None. If None.1 Table 1. axis]) Return the number of elements along a given axis. subok]) Return the data of a masked array as an ndarray.any(self.ma. axis=None. perform over flattened array.getmaskarray(arr) Return the mask of a masked array. then the output is masked. ma.3].size(obj[.any([axis. ma.81 – continued from previous page ma.count_masked(arr[.count([axis]) Count the non-masked elements of the array along the given axis.ma. ma. ma.nonzero(self) Return the indices of unmasked elements that are not zero.mask Mask ma.MaskedArray. optional Array into which the result can be placed.MaskedArray.recordmask Return the mask of the records. ma. Parameters axis : {None. or nomask. out]) Check if all of the elements of a are true. For convenience. array}. 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.size(obj[. integer} Axis to perform the operation over.2.array([1. axis]) Count the number of masked elements along the given axis.data Return the current data.3]). as a view of the original ma. axis]) Return the number of elements along a given axis.all([axis. ma.shape(obj) Return the shape of an array.getdata(a[.ma.shape(obj) Return the shape of an array. ma. Masked arrays 307 .

count(axis=0) array([1.reshape((2. Parameters arr : array_like 308 Chapter 1. :] = ma. mask = [[False False False] [ True True True]]. axis=None) Count the number of masked elements along the given axis. If axis is None. axis=None) Count the non-masked elements of the array along the given axis. optional Array into which the result can be placed. perform over flattened array and return a scalar.-.count() 3 When the axis keyword is specified an array of appropriate size is returned.NumPy Reference. an integer count is returned. optional Axis along which to count the non-masked elements.masked >>> a masked_array(data = [[0 1 2] [-. Its type is preserved and it must be of the right shape to hold the output. out : {None.ma.8. 1. Returns result : int or ndarray If axis is None.1 Axis to perform the operation over. See Also: count_masked Count masked elements in array or along a given axis. If None. Examples >>> import numpy. When axis is not None. 3)) >>> a[1. >>> a. 0]) numpy.--]].ma as ma >>> a = ma. Parameters axis : int. fill_value = 999999) >>> a. array}.count(a. an array with shape determined by the lengths of the remaining axes.count(axis=1) array([3. See Also: any equivalent function numpy.ma. Release 1. 1]) >>> a. Array objects . is returned.arange(6).count_masked(arr. all non-masked elements are counted.

mask = [[False False False] [ True False True] [False True False]]. 1]) >>> ma.count_masked(a) 3 When the axis keyword is used an array is returned.count Count non-masked elements. Examples >>> import numpy. 1. Parameters a : array_like Input MaskedArray for which the mask is required. axis : int.count_masked(a. >>> ma. 1]) numpy. 0] = ma. a flattened version of the array is used.reshape((3.1 An array with (possibly) masked elements.ma as ma >>> a = np. See Also: MaskedArray.7. 1] = ma. or nomask. Release 1.array(a) >>> a[1. Return the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask. Returns count : int.masked >>> a[1. 2. optional Axis along which to count.masked >>> a[2. To guarantee a full array of booleans of the same shape as a.8. Masked arrays 309 . 1. else return nomask.3)) >>> a = ma.ma. fill_value=999999) >>> ma.masked >>> a masked_array(data = [[0 1 2] [-.NumPy Reference.4 --] [6 -.count_masked(a. axis=0) array([1. ndarray The total number of masked elements (axis=None) or the number of masked elements along each slice of the given axis. axis=1) array([0.8]]. use getmaskarray.arange(9).getmask(a) Return the mask of a masked array. 2] = ma. If None (default). See Also: getdata Return the data of a masked array as an ndarray.

Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask.masked_array([[1.mask array([[False. True].4]].[3.1 getmaskarray Return the mask of a masked array. fill_value=999999) >>> ma.getmaskarray(arr) Return the mask of a masked array. See Also: getmask Return the mask of a masked array. mask = False.mask == ma. or full array of False. Array objects . Examples >>> import numpy.[3.8.nomask True >>> b. [False. False]].masked_equal([[1.ma as ma >>> a = ma. fill_value=999999) >>> ma.nomask True numpy. >>> a. mask = [[False True] [False False]].nomask False >>> ma. getdata Return the data of a masked array as an ndarray. True]. dtype=bool) Equivalently use the MaskedArray mask attribute. Release 1.4]]) >>> b masked_array(data = [[1 2] [3 4]].2].2]. [False. False]]. or nomask. or full boolean array of False.getmask(a) array([[False.getmask(b) == ma. Parameters arr : array_like Input MaskedArray for which the mask is required. 310 Chapter 1.NumPy Reference. else return a full boolean array of False of the same shape as arr. dtype=bool) Result when mask == nomask >>> b = ma.ma. 2) >>> a masked_array(data = [[1 --] [3 4]].

getmaskarray(a) array([[False.[3.2]. mask = False.8. [False.4]]. 2) >>> a masked_array(data = [[1 --] [3 4]]. subok : bool Whether to force the output to be a pure ndarray (False) or to return a subclass of ndarray if appropriate (True. False]].7. 2) >>> a masked_array(data = [[1 --] 1.NumPy Reference. fill_value=999999) >>> >ma. dtype=bool) Result when mask == nomask >>> b = ma. Release 1. Parameters a : array_like Input MaskedArray.masked_equal([[1. False]]. getmaskarray Return the mask of a masked array. [False. default).[3.[3. alternatively a ndarray or a subclass thereof. Return the data of a (if any) as an ndarray if a is a MaskedArray. Masked arrays 311 .masked_array([[1.ma as ma >>> a = ma.2].2].4]]) >>> b masked_array(data = [[1 2] [3 4]]. True]. dtype=bool) numpy. subok=True) Return the data of a masked array as an ndarray.getmaskarray(b) array([[False. mask = [[False True] [False False]].getdata(a.4]].ma.ma as ma >>> a = ma.1 Examples >>> import numpy.masked_equal([[1. else return a as a ndarray or subclass (depending on subok) if not. or full array of False. False]. See Also: getmask Return the mask of a masked array. Examples >>> import numpy. or nomask. fill_value=999999) >>> ma.

transpose(a. 1. The corresponding non-zero values can be obtained with: a[a. rather than dimension.8. 0. 0. 0. >>> a. Examples >>> import numpy.nonzero Equivalent ndarray method. mask = [[False True] [False False]].nonzero(self ) = <numpy.getdata(a) array([[1. one for each dimension. containing the indices of the non-zero elements in that dimension.1 [3 4]]. flatnonzero Return indices that are non-zero in the flattened version of the input array. 1. count_nonzero Counts the number of non-zero elements in the input array. mask = 312 Chapter 1.nonzero()] To group the indices by element.ma as ma >>> x = ma.nonzero()) The result of this is always a 2d array.] [ 0. use instead: np. Parameters None Returns tuple_of_arrays : tuple Indices of elements that are non-zero.NumPy Reference. 4]]) numpy. See Also: numpy.ma.eye(3)) >>> x masked_array(data = [[ 1. Returns a tuple of arrays. with a row for each non-zero element.nonzero Function operating on ndarrays. 0. fill_value=999999) >>> ma.core.array(np. 2]. ndarray.]]. [3. Array objects ._frommethod instance at 0x28204d0> Return the indices of unmasked elements that are not zero. [3. 2].data array([[1.] [ 0. 4]]) Equivalently use the MaskedArray data attribute. Release 1.ma.

1. mask = [[False False False] [False True False] [False False False]].0 1.nonzero()) array([[0.2.0 0. 2])) The nonzero method of the condition array can also be called.[7.[4. 2.ma. >>> x[1.9]]) >>> a > 3 masked_array(data = [[False False False] [ True True True] [ True True True]]. 2. 2])) Masked elements are ignored.0]].0 0.shape(obj) Return the shape of an array. mask = False. ma. 1.8. where a condition is True.0 -. >>> (a > 3). 0. 1. 1] = ma. 1. 2]). 2. 2]]) A common use for nonzero is to find the indices of an array.3]. array([0. 1.nonzero() (array([0.0 0.array([[1.nonzero(a > 3) yields the indices of the a where the condition is true.7. 2]).8. 1. 2.NumPy Reference. Parameters a : array_like Input array. 1. Given an array a.masked >>> x masked_array(data = [[1. 1. 2. array([0.1 False. 0]. >>> a = ma.5.transpose(x. 2])) Indices can also be grouped by element. >>> np. array([0. array([0.6]. the condition a > 3 is a boolean array and since False is interpreted as 0. Returns shape : tuple of ints The elements of the shape tuple give the lengths of the corresponding array dimensions. 2]). 0. 1. Masked arrays 313 . 2]). 2.nonzero(a > 3) (array([1.0] [0. fill_value=1e+20) >>> x. [2. 1.nonzero() (array([0. 1. fill_value=999999) >>> ma. 2])) numpy. Release 1.0] [0.nonzero() (array([1. fill_value=1e+20) >>> x.0.

shape dimensions of array ndarray.size number of elements in array Examples >>> >>> 6 >>> 3 >>> 2 314 a = np. 3) >>> np.3]. (’y’. Array objects .) numpy. Release 1.0) Chapter 1. 2) >>> np.eye(3)) (3.size(a) np. 2).size(a. Parameters a : array_like Input data.) >>> np.array([(1.) >>> a.1) np.5. axis : int.2.shape Equivalent array method. ’i4’). By default. Returns element_count : int Number of elements along the specified axis.shape([0]) (1.NumPy Reference. (3.shape (2.ma.shape(a) (2.shape([[1.size(obj. axis=None) Return the number of elements along a given axis.shape(np.1 See Also: alen ndarray. ’i4’)]) >>> np.size(a. optional Axis along which the elements are counted. See Also: shape dimensions of array ndarray.shape(0) () >>> a = np.[4.array([[1.6]]) np. 4)]. Examples >>> np. 2]]) (1.8. give the total number of elements. dtype=[(’x’.

Masked values are considered as False during computation. then the output is masked. Masked arrays 315 . optional Array into which the result can be placed. out : {None. integer} Axis to perform the operation over. If None. Performs a logical_or over the given axis and returns the result. MaskedArray.data Return the current data.8. Its type is preserved and it must be of the right shape to hold the output. Masked values are considered as True during computation. optional Array into which the result can be placed. Parameters axis : {None. out=None) Check if all of the elements of a are true. A record is masked when all the fields are masked. Performs a logical_and over the given axis and returns the result.recordmask Return the mask of the records. perform over flattened array and return a scalar. perform over flattened array.3]. See Also: any equivalent function 1. Parameters axis : {None. MaskedArray.3]).all() True >>> a = np.all() is np. mask=True) >>> (a.masked) True MaskedArray.any(axis=None. out=None) Check if any of the elements of a are true.2. If None. 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. array}.ma. array}.NumPy Reference. Its type is preserved and it must be of the right shape to hold the output. integer} Axis to perform the operation over.mask Mask MaskedArray. See Also: all equivalent function Examples >>> np.1 MaskedArray. as a view of the original underlying data.array([1. For convenience.7. out : {None.ma.ma. Release 1.2.all(axis=None.array([1.

:] = ma.count() 3 When the axis keyword is specified an array of appropriate size is returned. Parameters None Returns tuple_of_arrays : tuple 316 Chapter 1. The corresponding non-zero values can be obtained with: a[a. fill_value = 999999) >>> a. 0]) MaskedArray. an integer count is returned. is returned. optional Axis along which to count the non-masked elements. rather than dimension.count(axis=1) array([3.count(axis=None) Count the non-masked elements of the array along the given axis.nonzero()) The result of this is always a 2d array.transpose(a.nonzero() Return the indices of unmasked elements that are not zero.-. containing the indices of the non-zero elements in that dimension. Returns result : int or ndarray If axis is None. 1]) >>> a. 1.arange(6).--]]. Array objects . When axis is not None. an array with shape determined by the lengths of the remaining axes. one for each dimension.ma as ma >>> a = ma.nonzero()] To group the indices by element.1 MaskedArray.NumPy Reference. >>> a. Returns a tuple of arrays. 3)) >>> a[1. If axis is None.reshape((2. See Also: count_masked Count masked elements in array or along a given axis. Release 1.8. Parameters axis : int. mask = [[False False False] [ True True True]].masked >>> a masked_array(data = [[0 1 2] [-. with a row for each non-zero element.count(axis=0) array([1. all non-masked elements are counted. use instead: np. Examples >>> import numpy.

nonzero Equivalent ndarray method.0 0.nonzero() (array([0. array([0.0 0. 1] = ma. Masked arrays 317 .] [ 0. Examples >>> import numpy.1 Indices of elements that are non-zero.8. [2. 2]]) A common use for nonzero is to find the indices of an array.] [ 0.3].NumPy Reference.nonzero(a > 3) yields the indices of the a where the condition is true. the condition a > 3 is a boolean array and since False is interpreted as 0.[4.transpose(x.9]]) >>> a > 3 masked_array(data = 1.7.8. array([0. 2])) Masked elements are ignored. count_nonzero Counts the number of non-zero elements in the input array. 1. 0. fill_value=1e+20) >>> x.]].0] [0.nonzero Function operating on ndarrays. 0]. 0. flatnonzero Return indices that are non-zero in the flattened version of the input array.2. ma. 0.5.masked >>> x masked_array(data = [[1.0 1. 0. fill_value=1e+20) >>> x. >>> np.nonzero()) array([[0. mask = False.array([[1.6].ma as ma >>> x = ma. 2]).[7. >>> x[1.0] [0. Release 1. 1.0 0. See Also: numpy. Given an array a. 2]). 1.eye(3)) >>> x masked_array(data = [[ 1.0. 2])) Indices can also be grouped by element.0 -.nonzero() (array([0. >>> a = ma. 1. ndarray. mask = [[False False False] [False True False] [False False False]].array(np. where a condition is True.0]].

2]). 1. 2])) The nonzero method of the condition array can also be called. 0. 2) >>> np. 1.shape([[1.shape([0]) (1.1 [[False False False] [ True True True] [ True True True]]. 2]]) (1. 2.eye(3)) (3.NumPy Reference.shape(0) () >>> a = np.size(obj.) numpy. 2])) numpy.nonzero() (array([1.shape(obj) Return the shape of an array. array([0. dtype=[(’x’. See Also: alen ndarray.shape (2. 2). (3.shape(np. axis : int. axis=None) Return the number of elements along a given axis. optional 318 Chapter 1. (’y’.shape(a) (2. Parameters a : array_like Input array. Release 1. 2. Returns shape : tuple of ints The elements of the shape tuple give the lengths of the corresponding array dimensions.) >>> np. 1. Parameters a : array_like Input data. 2.ma. 2.) >>> a. 1.array([(1. >>> (a > 3). ’i4’). 2]). 4)]. Array objects . 2. 1.nonzero(a > 3) (array([1. ’i4’)]) >>> np. array([0. fill_value=999999) >>> ma.shape Equivalent array method. 1. Examples >>> np. 2. 1. 3) >>> np.8. 0. mask = False. 1.ma.

array([[1.shape).ma.MaskedArray.resize(newshape[.size number of elements in array Examples >>> >>> 6 >>> 3 >>> 2 a = np. **kwargs) ma. (self. new_shape) ma. as a view.NumPy Reference. Returns a 1D version of self.flatten([order]) ma.reshape(*s.size.[4.2. By default.ma..) (or Examples >>> x = np. give the total number of elements.6].ravel(self ) = <numpy.array([[1.1 Axis along which the elements are counted.ravel() ma. mask=[0] + [1.)).size(a. Masked arrays 319 .5.[4. See Also: shape dimensions of array ndarray.resize(x. Return a new masked array with the specified size and shape. as a view.size(a.MaskedArray.9]].[7.7.2.reshape(a. Release 1.8.5.0) Manipulating a MaskedArray Changing the shape ma.1) np. as a view.MaskedArray.3] 1..MaskedArray. . order]) ma.3].ravel(self) ma. Returns MaskedArray Output view is of shape (np.8.core.ma. Return a copy of the array collapsed into one dimension.]) Returns a 1D version of self.0]*4) >>> print x [[1 -.6]]) np.ma. Returns element_count : int Number of elements along the specified axis. Give a new shape to the array without changing its data.3].size(a) np. Returns an array containing the same data with a new shape. new_shape[. numpy._frommethod instance at 0x2820680> Returns a 1D version of self.shape dimensions of array ndarray.product(self. refcheck.

NumPy Reference.resize(a. fill_value = 999999) >>> np.reshape for full documentation. Array objects . 1.9] numpy. The new array is filled with repeated copies of x (in the order that the data are stored in memory). [3. If x is masked.ravel() [1 -.resize(x.3] [4 1 --] [3 4 1]].3 -. This is the masked equivalent of the numpy.reshape equivalent function numpy.8.[3.resize Equivalent function in the top level NumPy module.7 -. >>> a = np.reshape(a. (3. (3.ma.masked >>> a masked_array(data = [[1 --] [3 4]]. [4. 2] . mask = [[False True False] [False False True] [False False False]]. 4]]) >>> a[0.9]] >>> print x.resize(a. and the new mask will be a repetition of the old one. 4]]) >>> ma. 2] . Examples >>> import numpy. fill_value = 999999) A MaskedArray is always returned.resize(a. 1] = ma.array([[1. See Also: numpy. new_shape. Refer to MaskedArray. mask = [[False True] [False False]]. new_shape) Return a new masked array with the specified size and shape.1 [-. 2. 3)) array([[1. See Also: MaskedArray. 4.[3. the new array will be masked. order=’C’) Returns an array containing the same data with a new shape. 3]. (3. 3)) 320 Chapter 1.ma as ma >>> a = ma. 1]]) >>> ma. 3)) masked_array(data = [[1 -. regardless of the input type. 2].5 --] [7 -.resize function. Release 1.ma.array([[1.5 -.

3 -. 2.product(self. optional Whether to flatten in C (row-major).flatten(order=’C’) Return a copy of the array collapsed into one dimension.ma.3]. Fortran (column-major) order. mask = False. 4]) >>> a.2].2. Returns MaskedArray Output view is of shape (np. Returns y : ndarray A copy of the input array.reshape(*s.7 -. ‘A’}. 1.1 masked_array(data = [[1 2 3] [4 1 2] [3 4 1]].6].array([[1. Masked arrays 321 .5.[4. fill_value = 999999) MaskedArray.array([[1.5 -. Examples >>> a = np.9] MaskedArray. 2.[7. mask=[0] + [1. The default is ‘C’.ravel() [1 -.7. 4]) MaskedArray.0]*4) >>> print x [[1 -.8. 3.ma.shape). ‘F’. flattened to one dimension. Parameters order : {‘C’.size. flat A 1-D flat iterator over the array.8.5 --] [7 -. or preserve the C/Fortran ordering from a.9]] >>> print x. See Also: ravel Return a flattened array. as a view.4]]) >>> a.flatten() array([1. 3. **kwargs) Give a new shape to the array without changing its data.NumPy Reference.flatten(’F’) array([1.9]]. (self.3] [-.) (or Examples >>> x = np.)).ravel() Returns a 1D version of self. [3. Release 1.

reshape Equivalent function in the NumPy module.2]. A masked array does not own its data and therefore cannot safely be resized in place. numpy.resize function instead. optional Determines whether the array data should be viewed as in C (row-major) or FORTRAN (column-major) order. refcheck=True. Array objects .NumPy Reference. Use the numpy. order=False) Warning: This method does nothing.ndarray.4]].1 Returns a masked array containing the same data.1)) >>> print x [[--] [2] [3] [--]] MaskedArray.2] [3 --]] >>> x = x. The result is a view on the original array. See Also: reshape Equivalent function in the masked array module. ‘F’}.reshape Equivalent method on ndarray object. axes]) swapaxes Permute the dimensions of an array. Modifying axes ma.transpose(a[. numpy.shape = s Examples >>> x = np. order : {‘C’.0. use a. This method is difficult to implement safely and may be deprecated in future releases of NumPy.resize(newshape. if this is not possible.reshape((4. Returns reshaped_array : array A new view on the array. then the result will be a 1-D array of that length. Release 1.0. a ValueError is raised.1]) >>> print x [[-. except raise a ValueError exception. Notes The reshaping operation cannot guarantee that a copy will not be made. but with a new shape.8. mask=[1. to modify the shape in place.swapaxes ma. Continued on next page 322 Chapter 1.ma.[3.array([[1. Parameters shape : int or tuple of ints The new shape should be compatible with the original shape. If an integer is supplied.ma.

fill_value = 999999) >>> ma.ma as ma >>> x = ma.7.core.swapaxes(axis1.MaskedArray.8. Refer to numpy.transpose(*axes) Returns a view of the array with axes transposed.swapaxes equivalent function 1.swapaxes for full documentation.reshape((2._frommethod instance at 0x2820998> swapaxes a.swapaxes equivalent function numpy. Release 1.1 Table 1.swapaxes(axis1.NumPy Reference.2)) >>> x[1.swapaxes = <numpy. Examples >>> import numpy. See Also: numpy. axis2) Return a view of the array with axis1 and axis2 interchanged. mask = [[False False] [False True]]. Refer to numpy. 1] = ma.transpose(a.swapaxes for full documentation. mask = [[False False] [False True]].arange(4).83 – continued from previous page ma.transpose. numpy. fill_value = 999999) MaskedArray.ma.transpose Equivalent function in top-level NumPy module. axis2) Return a view of the array with axis1 and axis2 interchanged. ma.ma. This function is exactly equivalent to numpy.masked >>>> x masked_array(data = [[0 1] [2 --]]. axes=None) Permute the dimensions of an array.ma.transpose(x) masked_array(data = [[0 2] [1 --]].swapaxes(axis1.MaskedArray. Masked arrays 323 . See Also: numpy. axis2) Return a view of the array with axis1 and axis2 interchanged. See Also: numpy.

Continued on next page Chapter 1. axis]) ma. 2]. Concatenate a sequence of arrays along the given axis. Remove single-dimensional entries from the shape of an array. View inputs as arrays with at least two dimensions. 4]]) >>> a.atleast_3d(*arys) ma... i[n-2].) For a 2-D array. Stack arrays in sequence horizontally (column wise). . • 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.NumPy Reference.transpose(*axes) Returns a view of the array with axes transposed. or n ints • None or no argument: reverses the order of the axes.squeeze([axis]) ma. 3].concatenate(arrays[. tuple of ints.atleast_1d(*arys) ma. [2. View inputs as arrays with at least three dimensions. this has no effect. (To change between column and row vectors.dstack(tup) ma. For an n-D array.squeeze(a[. [2. 3].transpose((1. Remove single-dimensional entries from the shape of a. Stack arrays in sequence depth wise (along third axis). 0) array([[1. 2]. . [2. if axes are given. this is the usual matrix transpose.expand_dims(x. 4]]) Changing the number of dimensions ma. • tuple of ints: i in the j-th place in the tuple means a‘s i-th axis becomes a.. i[0]). See Also: ndarray. first cast the 1-D array into a matrix object. then a.column_stack(tup) ma.1 MaskedArray. Expand the shape of an array. i[n-1]). [3. 4]]) >>> a. [3. 4]]) >>> a array([[1.transpose(1.8.shape = (i[0].transpose()‘s j-th axis.atleast_2d(*arys) ma. Examples >>> a = np. For a 1-D array. i[n-2]. Parameters axes : None.transpose(). Array objects . 0)) array([[1. 4]]) >>> a. i[1]. with axes suitably permuted. axis]) ma.T Array property returning the array transposed. Release 1.shape = (i[n-1]. axis) ma.MaskedArray.hstack(tup) 324 Convert inputs to arrays with at least one dimension. their order indicates how the axes are permuted (see Examples). If axes are not provided and a. 3].transpose() array([[1. i[1].array([[1.. Stack 1-D arrays as columns into a 2-D array.

res2. 4])] numpy.0). Scalar inputs are converted to 1-dimensional arrays.84 – continued from previous page ma. Returns res.extras. Release 1. 2. 8.ma. each with a.].]) >>> x = np. .vstack(tup) Stack arrays in sequence vertically (row wise). Notes The function is applied to both the _data and the _mask.row_stack(tup) Stack arrays in sequence vertically (row wise).. 1. : array_like One or more array-like sequences. 7. or sequence of arrays.atleast_1d(x) is x True >>> np. [ 6.NumPy Reference.. ma. Arrays that already have two or more dimensions are preserved.. [ 3. Copies are avoided where possible... .ma.atleast_1d(*arys) = <numpy. Copies are made only if necessary. Examples >>> np.arange(9.]. Non-array inputs are converted to arrays..ndim >= 2.extras. if any. Masked arrays 325 .atleast_1d(1. arys2. 4._fromnxfunction instance at 0x28217e8> View inputs as arrays with at least two dimensions...1 Table 1. ma.reshape(3.mr_ Translate slice objects to concatenation along the first axis. and views with two or more dimensions are returned. or tuple of arrays. array([3. 4]) [array([1]).ndim >= 1. Returns ret : ndarray An array.0) array([ 1.atleast_1d(1. 5.._fromnxfunction instance at 0x28216c8> Convert inputs to arrays with at least one dimension. arys2. whilst higher-dimensional inputs are preserved. 1..ma.atleast_2d(*arys) = <numpy. Parameters arys1.. [3.]]) >>> np. : ndarray An array.atleast_1d(x) array([[ 0. : array_like One or more input arrays. indices_or_sections) Split an array into multiple sub-arrays horizontally (column-wise).3) >>> np.hsplit(ary. . Parameters arys1.ma. each with a.7.8. ma. numpy..

atleast_2d(x) array([[ 0.. arr. [[1.. : array_like One or more array-like sequences.atleast_3d(x). a 1-D array of shape (N.arange(3. Non-array inputs are converted to arrays.NumPy Reference. array([[1. 1). Returns res1.shape (1.3) >>> np. 2]])] numpy. if any. Examples >>> np.0) array([[[ 3. and a 2-D array of shape (M.0) array([[ 3. array([[1. 2]].reshape(4. [[1. 1)._fromnxfunction instance at 0x2821878> View inputs as arrays with at least three dimensions. N) becomes a view of shape (M.ma.atleast_3d([1. 1. 3.atleast_3d(x).extras.shape . . Examples >>> np. N. print arr.base is x True >>> np. each with a.atleast_3d(x). Array objects ..atleast_2d(1. [1.base is x True >>> for arr in np..ndim >= 3. 2]]) [array([[1]]).atleast_2d(3. : ndarray An array.atleast_3d(3.]]]) >>> x = np. [[[1] 326 Chapter 1. 2]]). . if any.0) >>> np.arange(3..0) >>> np.1 Notes The function is applied to both the _data and the _mask.]]) >>> np.0).atleast_3d(*arys) = <numpy.atleast_2d(x). 2]. or tuple of arrays. For example.8. 1) >>> np. Parameters arys1. 2.) becomes a view of shape (1. 2]. Copies are avoided where possible.. Notes The function is applied to both the _data and the _mask.]]) >>> x = np. N. Release 1..ma. arys2.. [[[1.shape (4.. res2.arange(12. Arrays that already have three or more dimensions are preserved. 1) >>> x = np. 3.. 2]]]): . and views with three or more dimensions are returned.

4]]) >>> ma. 2) numpy.expand_dims(x. axis) Expand the shape of an array.newaxis. >>> x[np.array([1.ma. fill_value = 999999) >>> np. Returns squeezed : ndarray The input array. Release 1. axis=0) masked_array(data = [[1 -. fill_value = 999999) numpy.7.4]]. axis=None) Remove single-dimensional entries from the shape of an array. Masked arrays 327 .1 [2]]] (1. Examples >>> import numpy.expand_dims Equivalent function in top-level NumPy module. This is always a itself or a view into a. optional New in version 1.ma.squeeze(a. mask = [False True False]. See Also: numpy.4]]. 1.0.expand_dims(x. Parameters a : array_like Input data. 1. 1) [[[1 2]]] (1.expand_dims(x. 2. 2. This function behaves the same as numpy. mask = [[False True False]]. mask = [[False True False]]. 2.expand_dims but preserves masked elements.7.8.4]. an error is raised.newaxis. axis : None or int or tuple of ints. 4]) >>> x[1] = ma.NumPy Reference. but with with all or a subset of the dimensions of length 1 removed. If an axis is selected with shape entry greater than one. :] masked_array(data = [[1 -. Selects a subset of the single-dimensional entries in the shape. Expands the shape of the array by including a new axis before the one specified by the axis parameter.ma as ma >>> x = ma.masked >>> x masked_array(data = [1 -. axis=0) array([[1. 2. 1) [[[1] [2]]] (1. fill_value = 999999) The same result can be achieved using slicing syntax with np.

4]]) numpy. [2]]]) >>> x.ma.4)) >>> np. [1].ma.NumPy Reference. 2].squeeze(axis=None) Remove single-dimensional entries from the shape of a.shape (3. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array.column_stack(tup) = <numpy. Arrays to stack. if any. 3. 3) MaskedArray. [2. 2-D arrays are stacked as-is. except in the dimension corresponding to axis (the first.b)) array([[1. See Also: numpy.3)) >>> b = np. optional 328 Chapter 1.array([[[0]. axis : int. axis=(2. Array objects . All of them must have the same first dimension. Release 1. by default).8.ma.concatenate(arrays. Refer to numpy. [3. Parameters arrays : sequence of array_like The arrays must have the same shape. Examples >>> a = np.squeeze for full documentation. 1-D arrays are turned into 2-D columns first.squeeze(x).squeeze equivalent function numpy. 3].extras.shape (1. just like with hstack.3.) >>> np.array((1. Returns stacked : 2-D array The array formed by stacking the given arrays. 1) >>> np.1 Examples >>> x = np.array((2.2. axis=0) Concatenate a sequence of arrays along the given axis. Notes The function is applied to both the _data and the _mask.shape (1.squeeze(x. Parameters tup : sequence of 1-D or 2-D arrays.column_stack((a._fromnxfunction instance at 0x2821a28> Stack 1-D arrays as columns into a 2-D array.)).

ma. 1.ma as ma >>> a = ma.2]. fill_value = 999999) numpy.NumPy Reference. mask = False. Masked arrays 329 . See Also: numpy.extras.concatenate([a.1 The axis along which the arrays will be joined. hstack Stack along second axis. b]) masked_array(data = [0 -. Takes a sequence of arrays and stack them along the third axis to make a single array.7.dstack(tup) = <numpy. 5) >>> a masked_array(data = [0 -.ma. 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. Rebuilds arrays divided by dsplit._fromnxfunction instance at 0x2821ab8> Stack arrays in sequence depth wise (along third axis). Release 1.arange(2. Returns result : MaskedArray The concatenated array with any masked entries preserved. fill_value = 999999) >>> b masked_array(data = [2 3 4].arange(3) >>> a[1] = ma.concatenate Equivalent function in the top-level NumPy module. This is a simple way to stack 2D arrays (images) into a single 3D array for processing. fill_value = 999999) >>> ma. Parameters tup : sequence of arrays Arrays to stack. concatenate Join arrays. See Also: vstack Stack along first axis. Examples >>> import numpy.8.2 2 3 4].masked >>> b = ma. Default is 0. mask = [False True False]. mask = [False True False False False False].

array((2. 2].b)) array([[[1. concatenate Join a sequence of arrays together.b)) array([[[1.ma.[4]]) >>> np.[3]. [[2. dstack Stack arrays in sequence depth wise (along third axis).[2]. [2. Release 1. [3.1 dsplit Split array along third axis. hsplit Split array along second axis.dstack((a.3.NumPy Reference.array([[1]. Notes The function is applied to both the _data and the _mask. 4]]]) numpy.2.hstack(tup) = <numpy.extras. Take a sequence of arrays and stack them horizontally to make a single array.dstack((a. Examples >>> a = np. if any.array((1.3)) >>> b = np. 3]._fromnxfunction instance at 0x2821998> Stack arrays in sequence horizontally (column wise). Rebuild arrays divided by hsplit. Parameters tup : sequence of ndarrays All arrays must have the same shape along all but the second axis.array([[2].4)) >>> np.[3]]) >>> b = np.8. Notes The function is applied to both the _data and the _mask. if any. See Also: vstack Stack arrays in sequence vertically (row wise). Array objects . 4]]]) >>> a = np. [[3.ma. 2]]. 330 Chapter 1. 3]]. Returns stacked : ndarray The array formed by stacking the given arrays.

].. 14. array([[ 2.b)) array([1.[3]]) >>> b = np. 7. 5._fromnxfunction instance at 0x2821b00> Split an array into multiple sub-arrays horizontally (column-wise).]. 15..]. [ 12. [ 4. [ 6.b)) array([[1.]]). 4) >>> x array([[ 0.array([3.hstack((a. [ 14.array((2. [ 12. 7. 4]) >>> a = np.. hsplit is equivalent to split with axis=1..]. [ 12. 2]..[2]..hsplit(x.4)) >>> np.1 Examples >>> a = np.0)..].NumPy Reference. [ 15. 11.]. [ 8.ma. 13.. 1.]. array([]. 10.[4]]) >>> np. indices_or_sections) = <numpy. [3..array([[1].. [ 8.]]) >>> np.. [ 11. dtype=float64)] With a higher dimensional array the split is still along the second axis. 9. 5.. 6.7.ma. the array is always split along the second axis regardless of the array dimension.... 3.. [2. [ 7.]. np. 9. 2) [array([[ 0. 1.hsplit(x. [ 4..]. 3. 6. Notes The function is applied to both the _data and the _mask.].. [ 8. 2. Examples >>> x = np.[3]. 1. [ 10.extras. 10. 3].. Please refer to the split documentation. 1.2. 9. 13.. array([[ 3.. 3.]]). Release 1. 5.].arange(16.hstack((a. [ 4.array([[2].3)) >>> b = np. Masked arrays 331 ...]]).].]])] >>> np. if any..]. 4]]) numpy..hsplit(ary.. 6])) [array([[ 0.array((1. 2. 15..8.3. 14. 3.. 2. See Also: split Split an array into multiple sub-arrays of equal size.]. 2. 11.reshape(4. 13.].

2.arange(8. Array objects . 332 Chapter 1. 2) >>> x array([[[ 0.NumPy Reference.8. The arrays must have the same shape along all but the first axis. [[ 4.. 2.ma. 0. 5. 3..].. 7.ma. 3.ma.row_stack(tup) = <numpy.1 >>> x = np..RClass. 5.ma.index_tricks. concatenate Join a sequence of arrays together. array([[[ 2. 1.]. 5.]]])] numpy. 0.extras. 6]) numpy. Returns stacked : ndarray The array formed by stacking the given arrays. [ 6.3]).]].mr_[np.ma. vsplit Split array into a list of multiple sub-arrays vertically.index_tricks. See Also: lib. 4.. This is the masked array version of lib.5.0). 1.6])] array([1. 0. 0. Take a sequence of arrays and stack them vertically to make a single array.]].array([1.mr_ = <numpy. 2) [array([[[ 0...ma. See Also: hstack Stack arrays in sequence horizontally (column wise). [[ 6.array([4.ma.extras. np. dstack Stack arrays in sequence depth wise (along third dimension). Release 1. Rebuild arrays divided by vsplit.]]. 2.hsplit(x._fromnxfunction instance at 0x2821908> Stack arrays in sequence vertically (row wise).RClass Examples >>> np. [[ 4. 3. Parameters tup : sequence of ndarrays Tuple containing arrays to be stacked.reshape(2.]]]).mr_class object at 0x281edd0> Translate slice objects to concatenation along the first axis. [ 2.. 7.]]]) >>> np.

array([[2]. if any.1 Notes The function is applied to both the _data and the _mask. [3].ma. [2. 4]) >>> np.vstack((a. [3]]) >>> b = np. Release 1.b)) array([[1. See Also: hstack Stack arrays in sequence horizontally (column wise). Returns stacked : ndarray The array formed by stacking the given arrays.7.8.NumPy Reference. Take a sequence of arrays and stack them vertically to make a single array. concatenate Join a sequence of arrays together. [4]]) numpy. 3]) >>> b = np.array([1. 4]]) >>> a = np.extras. if any. Rebuild arrays divided by vsplit. [2]. Notes The function is applied to both the _data and the _mask. vsplit Split array into a list of multiple sub-arrays vertically. 1.b)) array([[1]. 3]. 2. The arrays must have the same shape along all but the first axis. [4]]) >>> np. Masked arrays 333 . 2._fromnxfunction instance at 0x2821908> Stack arrays in sequence vertically (row wise).vstack(tup) = <numpy. 3. Parameters tup : sequence of ndarrays Tuple containing arrays to be stacked.vstack((a.ma. Examples >>> a = np.array([[1]. [2]. [3]. [3]. dstack Stack arrays in sequence depth wise (along third dimension).array([2. [2]. 3.

hstack(tup) ma. 3. 2-D arrays are stacked as-is. axis=0) Concatenate a sequence of arrays along the given axis.vstack(tup) Stack 1-D arrays as columns into a 2-D array. Returns stacked : 2-D array The array formed by stacking the given arrays. numpy.dstack(tup) ma. [2]. 1-D arrays are turned into 2-D columns first.column_stack(tup) = <numpy.2. 4]) >>> np.array((1. 2]. [4]]) >>> np. Stack arrays in sequence depth wise (along third axis). 3. Examples >>> a = np. just like with hstack.1 Examples >>> a = np.8.column_stack(tup) ma. 2.vstack((a. Notes The function is applied to both the _data and the _mask.extras. [4]]) Joining arrays ma.3)) >>> b = np. Concatenate a sequence of arrays along the given axis. 334 Chapter 1.concatenate(arrays.4)) >>> np. 4]]) >>> a = np. All of them must have the same first dimension. [3.b)) array([[1]. [3]. 3]. Arrays to stack.ma. [3]._fromnxfunction instance at 0x2821a28> Stack 1-D arrays as columns into a 2-D array. Stack arrays in sequence horizontally (column wise).ma. 4]]) numpy. 3]. [2]. Array objects . Stack arrays in sequence vertically (row wise).array([[1]. Release 1.3. Parameters tup : sequence of 1-D or 2-D arrays. 3]) >>> b = np.b)) array([[1.array((2. [2].concatenate(arrays[. if any.array([1. axis]) ma.array([[2].b)) array([[1.array([2. [3].column_stack((a.NumPy Reference.vstack((a. [3]]) >>> b = np. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2. [2.ma. [2.

arange(3) >>> a[1] = ma. by default). Takes a sequence of arrays and stack them along the third axis to make a single array.7.arange(2. axis : int. Parameters tup : sequence of arrays Arrays to stack.dstack(tup) = <numpy.extras.8.NumPy Reference. 5) >>> a masked_array(data = [0 -.masked >>> b = ma. See Also: 1. mask = False. mask = [False True False].ma.2]. fill_value = 999999) numpy.concatenate([a.ma. This is a simple way to stack 2D arrays (images) into a single 3D array for processing. All of them must have the same shape along all but the third axis. Masked arrays 335 . Default is 0. Examples >>> import numpy.2 2 3 4]. b]) masked_array(data = [0 -.concatenate Equivalent function in the top-level NumPy module. Returns stacked : ndarray The array formed by stacking the given arrays. fill_value = 999999) >>> ma. Rebuilds arrays divided by dsplit.1 Parameters arrays : sequence of array_like The arrays must have the same shape. optional The axis along which the arrays will be joined. fill_value = 999999) >>> b masked_array(data = [2 3 4]. Returns result : MaskedArray The concatenated array with any masked entries preserved. except in the dimension corresponding to axis (the first. See Also: numpy. mask = [False True False False False False].ma as ma >>> a = ma. Release 1._fromnxfunction instance at 0x2821ab8> Stack arrays in sequence depth wise (along third axis).

336 Chapter 1. Parameters tup : sequence of ndarrays All arrays must have the same shape along all but the second axis. Take a sequence of arrays and stack them horizontally to make a single array. hstack Stack along second axis.[3]]) >>> b = np. 4]]]) numpy.array([[1]. 3]. Array objects .8. [3.1 vstack Stack along first axis.2. 4]]]) >>> a = np.NumPy Reference.b)) array([[[1. [2.array([[2].4)) >>> np. Returns stacked : ndarray The array formed by stacking the given arrays. concatenate Join arrays. concatenate Join a sequence of arrays together. 2].extras. See Also: vstack Stack arrays in sequence vertically (row wise).b)) array([[[1. dsplit Split array along third axis._fromnxfunction instance at 0x2821998> Stack arrays in sequence horizontally (column wise).[4]]) >>> np. dstack Stack arrays in sequence depth wise (along third axis).ma. Examples >>> a = np.[2].3. [[3.3)) >>> b = np.[3]. [[2.hstack(tup) = <numpy. Notes The function is applied to both the _data and the _mask. if any.array((2.dstack((a. Release 1.array((1. 2]]. Rebuild arrays divided by hsplit.dstack((a.ma. 3]].

8. Masked arrays 337 . 3]. [3. Rebuild arrays divided by vsplit. Examples >>> a = np. dstack Stack arrays in sequence depth wise (along third dimension). Returns stacked : ndarray The array formed by stacking the given arrays.1 hsplit Split array along second axis.7. 2.2.extras.3)) >>> b = np. Notes The function is applied to both the _data and the _mask. vsplit Split array into a list of multiple sub-arrays vertically. 3. 4]]) numpy._fromnxfunction instance at 0x2821908> Stack arrays in sequence vertically (row wise).[4]]) >>> np. Release 1. concatenate Join a sequence of arrays together.b)) array([[1.[2].vstack(tup) = <numpy. Notes The function is applied to both the _data and the _mask.array([[1]. 4]) >>> a = np.ma.array((1.[3]]) >>> b = np.NumPy Reference.hstack((a. 2]. The arrays must have the same shape along all but the first axis.3. if any. Examples 1. 2.array([[2]. if any.b)) array([1.array((2. [2.4)) >>> np.[3]. Take a sequence of arrays and stack them vertically to make a single array. Parameters tup : sequence of ndarrays Tuple containing arrays to be stacked. 3.hstack((a.ma. See Also: hstack Stack arrays in sequence horizontally (column wise).

each field has a boolean dtype.mask_or(m1. optional Whether to return a copy of m (True) or m itself (False).ma. copy=False. 3. m2[. Return m as a boolean mask. 3].make_mask_none(newshape[. dtype=<type ‘numpy. 4]) >>> np. copy. Release 1.array([2. Returns result : ndarray A boolean mask derived from m. Return a boolean mask of the given shape. [2].make_mask(m[. dtype : dtype. copy. shrink]) ma. [3]. shrink=True. 338 Chapter 1.8. The function can accept any sequence that is convertible to integers. creating a copy if necessary or requested.b)) array([[1]. or nomask. Parameters m : array_like Potential mask. [3]. numpy. dtype]) ma. everything else as True. copy : bool. [2. optional Data-type of the output mask.array([[2]. [3]. By default. Combine two masks with the logical_or operator. shrink : bool. Construct a dtype description list from a given dtype. shrink.1 >>> a = np. filled with False. 4]]) >>> a = np.bool_’>) Create a boolean mask from an array. [2]. optional Whether to shrink m to nomask if all its values are False.make_mask(m. [4]]) >>> np. [4]]) Operations on masks Creating a mask ma.b)) array([[1.array([[1].array([1. 3. the output mask has a dtype of MaskType (bool). Does not require that contents must be 0s and 1s. [2]. values of 0 are interepreted as False. 2.vstack((a. 2.vstack((a. dtype]) ma.NumPy Reference. Array objects . [3]]) >>> b = np. 3]) >>> b = np. If the dtype is flexible.make_mask_descr(ndtype) Create a boolean mask from an array.

1 Examples >>> import numpy.make_mask_none(newshape.. dtype=None) Return a boolean mask of the given shape. dtype=dtype) array([(True. True).zeros(4) >>> m array([ 0. False). Returns result : ndarray An ndarray of appropriate shape and dtype. False.make_mask(m) array([ True.ma. 1. If a complex dtype is specified. -3] >>> ma. dtype : {None. False]. False. ’formats’:[np. 0. False.make_mask(arr. (’mouse’. (1. Release 1. 0. 0. mouse in zip(m. ’mouse’]. 0). 0). dtype=bool) >>> m = [1. 0. dtype=bool) >>> m = [1.array(arr. False. (’mouse’. 1. False). Parameters newshape : tuple A tuple indicating the shape of the mask. converted to boolean types. True]. (1. Otherwise. 1. dtype=bool) Using a flexible dtype. dtype=bool) Effect of the shrink parameter. Masked arrays 339 . 1).dtype({’names’:[’man’.make_mask(m) False >>> ma. (False. (1. False. dtype=[(’man’. arr. 1] >>> n = [0. True. True]. >>> m = np.. that can be used in common mask manipulations. dtype}.NumPy Reference.make_mask(m) array([ True.make_mask(m. True. filled with False. shrink=False) array([False. ’<i4’). 0. filled with False. np. (True. This function returns a boolean ndarray with all entries False. 1. 0)]. 0). ’<i4’)]) >>> ma. (0. the type of each field is converted to a boolean type. 0). n): .int. dtype=[(’man’. True]. ’|b1’).ma as ma >>> m = [True. >>> m = [1. 0.append((man. use a new datatype with the same fields as dtype.]) >>> ma. use a MaskType instance.. (True.make_mask(m) array([ True.8. True] >>> ma. 1).int]}) >>> arr = np. ’|b1’)]) numpy.. True. dtype=dtype) >>> arr array([(1. optional If None. 0. 0] >>> arr = [] >>> for man. 0)] >>> dtype = np. False)]..7. 1] >>> ma. (1. False. True. (0. mouse)) >>> arr [(1. 2.

Release 1. ’bar’]. (’bar’. ’<f4’). dtype=dtype) array([(False. m2 : array_like Input masks. (’bar’. ’formats’:[np. optional If copy is False and one of the inputs is nomask.make_mask([1.ma. 1. 340 Chapter 1. ’|b1’)]) numpy.make_mask([0.float32. dtype=bool) numpy. False)]. True. 1. False). np. Examples >>> import numpy.)) array([False.ma as ma >>> ma.make_mask_descr(ndtype) Construct a dtype description list from a given dtype.). m2) array([ True. (False. return a view of the other input mask.int]}) >>> dtype dtype([(’foo’.make_mask_none((3.dtype({’names’:[’foo’. The result may be a view on m1 or m2 if the other is nomask (i.ma. Examples >>> m1 = np. dtype=[(’foo’. False). 0]) >>> np. False).8. >>> dtype = np.ma. (False. make_mask_descr Construct a dtype description list from a given dtype. dtype=bool) Defining a more complex dtype. Defaults to False.make_mask_none((3.ma. False]. shrink=True) Combine two masks with the logical_or operator. ’|b1’). False. 0. Defaults to True.e.1 See Also: make_mask Create a boolean mask from an array. shrink : bool. Parameters m1.ma.NumPy Reference. copy : bool. Array objects . optional Whether to shrink the output to nomask if all its values are False. 0.mask_or(m1. Returns mask : output mask The result masks values that are masked in either m1 or m2. Raises ValueError If m1 and m2 have different flexible dtypes. True.mask_or(m1. copy=False. False]. m2. ’<i4’)]) >>> ma. 0]) >>> m2 = np.

(’bar’.2]. (’bar’. Examples >>> import numpy. Masked arrays 341 . ’<i4’)]) >>> ma.masked_array.getmaskarray(arr) ma. or nomask.4]]. Release 1.int]}) >>> dtype dtype([(’foo’.make_mask_descr(np. Parameters a : array_like Input MaskedArray for which the mask is required. np. getmaskarray Return the mask of a masked array.masked_equal([[1.[3. use getmaskarray. See Also: getdata Return the data of a masked array as an ndarray. else return nomask. Field names are not altered.7. Return the mask of a as an ndarray if a is a MaskedArray and the mask is not nomask. ’|b1’). 2) >>> a masked_array(data = [[1 --] [3 4]]. or full boolean array of False.make_mask_descr(dtype) dtype([(’foo’. ’bar’].dtype({’names’:[’foo’. Examples >>> import numpy.ma as ma >>> a = ma. with the type of all fields in ndtype to a boolean type.float32.8. the type of all fields is boolean. or nomask.ma as ma >>> dtype = np. Returns result : dtype A dtype that looks like ndtype.bool_’> Accessing a mask ma.ma.getmask(a) Return the mask of a masked array.NumPy Reference.float32) <type ’numpy.1 Returns a new dtype object.mask Return the mask of a masked array.getmask(a) ma. Parameters ndtype : dtype The dtype to convert. mask = [[False True] 1. To guarantee a full array of booleans of the same shape as a. ’formats’:[np. or full array of False. ’<f4’). ’|b1’)]) >>> ma. Mask numpy. Return the mask of a masked array.

2]. Array objects .8.NumPy Reference.1 [False False]]. True]. >>> a. False]].masked_equal([[1.getmask(b) == ma.ma. [False. dtype=bool) Result when mask == nomask >>> b = ma. Examples >>> import numpy.nomask False >>> ma.nomask True >>> b. fill_value=999999) >>> ma.getmask(a) array([[False. See Also: getmask Return the mask of a masked array. 2) >>> a masked_array(data = [[1 --] [3 4]]. or full boolean array of False. getdata Return the data of a masked array as an ndarray. [False. else return a full boolean array of False of the same shape as arr.2].getmaskarray(arr) Return the mask of a masked array.mask array([[False.masked_array([[1. dtype=bool) Equivalently use the MaskedArray mask attribute. True]. Release 1.4]]) >>> b masked_array(data = [[1 2] [3 4]].[3. or nomask.ma as ma >>> a = ma.4]]. mask = [[False True] [False False]]. Parameters arr : array_like Input MaskedArray for which the mask is required.[3. mask = False. False]]. Return the mask of arr as an ndarray if arr is a MaskedArray and the mask is not nomask. fill_value=999999) >>> ma.nomask True numpy. fill_value=999999) 342 Chapter 1.mask == ma.

7.8.4]]) >>> b masked_array(data = [[1 2] [3 4]].flatnotmasked_edges(a) ma. numpy.flatnotmasked_contiguous(a) Find contiguous unmasked data in a masked array along the given axis. dtype=bool) Result when mask == nomask >>> b = ma.masked 1.2]. See Also: flatnotmasked_edges. dtype=bool) masked_array.getmaskarray(b) array([[False.ma. clump_masked.extras. axis]) ma.getmaskarray(a) array([[False. mask = False. clump_unmasked notmasked_contiguous.1 >>> ma. Find contiguous unmasked data in a masked array along the given axis. None) >>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np. True]. notmasked_edges. Find the indices of the first and last unmasked values along an axis. end index).arange(10) >>> np. False]].ma.notmasked_contiguous(a[. axis]) Find contiguous unmasked data in a masked array along the given axis. False]]. Find the indices of the first and last unmasked values.ma. Examples >>> a = np. Masked arrays 343 .[3. [False.ma. [False. False].flatnotmasked_contiguous(a) slice(0. Returns slice_list : list A sorted sequence of slices (start index. Parameters a : narray The input array. Release 1. Notes Only accepts 2-D arrays at most. fill_value=999999) >>> >ma.mask Mask Finding masked data ma.flatnotmasked_contiguous(a) ma. 10.notmasked_edges(a[.masked_array([[1.NumPy Reference.

notmasked_contiguous(a.ma. 7.masked >>> np. Expects a 1-D MaskedArray. Release 1. 5. Parameters a : array_like The input array. 6. notmasked_contiguous.extras.mask]) array([3.NumPy Reference. clump_unmasked Notes Only accepts 1-D arrays.arange(10) >>> flatnotmasked_edges(a) [0. Returns None if all values are masked. Array objects .flatnotmasked_contiguous(a) [slice(3. axis : int.ma. slice(6.ma. 8]) >>> np.ma.array(a[~a. 9.ma.1 >>> np.extras. 7.ma. Examples >>> a = np.ma.ma.mask]) array([3. 8]) >>> a[:] = np.-1] >>> mask = (a < 3) | (a > 8) | (a == 5) >>> a[mask] = np. 6. notmasked_edges. See Also: flatnotmasked_contiguous. optional 344 Chapter 1.masked >>> print np. 8]) >>> flatnotmasked_edges(a) array([3. axis=None) Find contiguous unmasked data in a masked array along the given axis.8.flatnotmasked_edges(a) Find the indices of the first and last unmasked values. 4. returns None if all values are masked. None). clump_masked.flatnotmasked_edges(a) None numpy.array(a[~a.masked >>> print flatnotmasked_edges(ma) None numpy. 4. None)] >>> a[:] = np. 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.

notmasked_contiguous. mask=mask) >>> np. clump_masked.reshape((3. slice(6. 6]) >>> np.ma. Returns endpoints : list A list of slices (start and end indexes) of unmasked indexes in the array. return None. 1:] = 1 >>> ma = np. 3)) >>> m = np.8. None). None)] numpy. If None (default).notmasked_contiguous(ma) [slice(0.zeros_like(a) >>> m[1:. 3)) >>> mask = np. clump_masked.array(a. clump_unmasked flatnotmasked_edges. 4. 2.arange(9).zeros_like(a) >>> mask[1:. Masked arrays 345 . optional Axis along which to perform the operation. edges is a list of the first and last index.NumPy Reference. If all values are masked. 1. See Also: flatnotmasked_contiguous. Otherwise.1 Axis along which to perform the operation.array(ma[~ma. Release 1. clump_unmasked Notes Only accepts 2-D arrays at most. Examples >>> a = np. See Also: flatnotmasked_edges.7.notmasked_edges(a. flatnotmasked_contiguous.extras. 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. corresponding to the indices of the first and last unmasked values respectively.mask]) array([0. If there are no masked data in the array. axis=None) Find the indices of the first and last unmasked values along an axis. 1:] = 1 1. axis : int. Parameters a : array_like The input array. Examples >>> a = np.ma. return a list of two tuples. 3.reshape((3. applies to a flattened version of the array.ma. 7.arange(9). notmasked_edges. If None (default).

mask_rowcols(a[. dtype=np. axis]) ma.mask_rows(a[. Force the mask to hard. fill_value=999999) >>> ma.MaskedArray. Mask rows of a 2D array that contain masked values.mask_or(m1.shrink_mask() ma. See Also: mask_rowcols Mask rows and/or columns of a 2D array. Force the mask to soft.harden_mask(self) ma. 0]. Combine two masks with the logical_or operator. 2.array(a. shrink]) ma. masked_where Mask where a condition is met.masked_equal(a. m2[. 6]) >>> np.mask_cols(a. 0]]) >>> a = ma. 0. 0. numpy. 1. 3). copy. [0. axis]) ma.soften_mask(self) ma.MaskedArray.unshare_mask() Mask columns of a 2D array that contain masked values.harden_mask() ma.0] 346 Chapter 1.zeros((3. 1) >>> a masked_array(data = [[0 0 0] [0 -. mask = [[False False False] [False True False] [False False False]]. Release 1.ma.ma. Copy the mask and set the sharedmask flag to False.0] [0 0 0]]. mask=m) >>> np. 0]. [0. Examples >>> import numpy.int) >>> a[1.notmasked_edges(ma) array([0.MaskedArray. 3.extras. Array objects .mask]) array([0.soften_mask() ma.mask_cols(a[.ma as ma >>> a = np.NumPy Reference. axis=None) Mask columns of a 2D array that contain masked values. axis]) ma.ma. Force the mask to hard.array(am[~am.mask_cols(a) masked_array(data = [[0 -. Force the mask to soft.MaskedArray. 1] = 1 >>> a array([[0.8. This function is a shortcut to mask_rowcols with axis equal to 1.1 >>> am = np. Mask rows and/or columns of a 2D array that contain masked values. 1. Reduce a mask to nomask when possible. 6]) Modifying a mask ma.

copy : bool. Raises ValueError If m1 and m2 have different flexible dtypes.e. Release 1. True.mask_or(m1.8. axis=None) Mask rows and/or columns of a 2D array that contain masked values. 1. •If axis is 0.ma. 1.make_mask([0. Defaults to True. optional If copy is False and one of the inputs is nomask. The result may be a view on m1 or m2 if the other is nomask (i.ma. m2) array([ True. return a view of the other input mask. axis : int.0] [0 -. fill_value=999999) numpy. dtype=bool) numpy. mask = [[False True False] [False True False] [False True False]]. True. Parameters m1. •If axis is 1 or -1. optional Whether to shrink the output to nomask if all its values are False. Parameters a : array_like. 0]) >>> np. optional 1. Defaults to False. m2 : array_like Input masks.0]]. Masked arrays 347 . 0]) >>> m2 = np. rows and columns are masked.ma. shrink=True) Combine two masks with the logical_or operator. Mask whole rows and/or columns of a 2D array that contain masked values. If not a MaskedArray instance (or if no array elements are masked). MaskedArray The array to mask. only columns are masked. 0. The masking behavior is selected using the axis parameter. False). •If axis is None.7. m2. False]. shrink : bool.make_mask([1. The result is a MaskedArray with mask set to nomask (False). 0.mask_rowcols(a. Must be a 2D array. copy=False. Returns mask : output mask The result masks values that are masked in either m1 or m2.ma.ma. only rows are masked.NumPy Reference. Examples >>> m1 = np.mask_or(m1.1 [0 -.

0].--] [0 -. Returns a : MaskedArray A modified version of the input array. Examples >>> import numpy. masked depending on the value of the axis parameter. fill_value=999999) >>> ma.ma as ma >>> a = np. 0. dtype=np. [0.zeros((3. 0]]) >>> a = ma. 3).0] [0 0 0]]. 0. 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. Raises NotImplementedError If input array a is not 2D.1 Axis along which to perform the operation. applies to a flattened version of the array. mask = [[False True False] [ True True True] [False True False]]. If None.8.int) >>> a[1. fill_value=999999) 348 Chapter 1. Notes The input array’s mask is modified by this function. Array objects . 1] = 1 >>> a array([[0. 0].mask_rowcols(a) masked_array(data = [[0 -.0]]. 1.NumPy Reference. Release 1.0] [-. masked_where Mask where a condition is met. mask = [[False False False] [False True False] [False False False]]. 1) >>> a masked_array(data = [[0 0 0] [0 -. [0.masked_equal(a.

masked_where Mask where a condition is met. axis=None) Mask rows of a 2D array that contain masked values.0] [0 0 0]]. mask = [[False False False] [False True False] [False False False]]. harden_mask sets hardmask to True.mask_rows(a. See Also: hardmask numpy.masked_equal(a.ma. 1] = 1 >>> a array([[0. See Also: mask_rowcols Mask rows and/or columns of a 2D array._frommethod instance at 0x2820368> Force the mask to hard.NumPy Reference.7. Whether the mask of a masked array is hard or soft is determined by its hardmask property.soften_mask(self ) = <numpy.core. fill_value=999999) >>> ma. mask = [[False False False] [ True True True] [False False False]]. Whether the mask of a masked array is hard or soft is determined by its hardmask property. 3). [0.harden_mask(self ) = <numpy.mask_rows(a) masked_array(data = [[0 0 0] [-. soften_mask sets hardmask to False. fill_value=999999) numpy. dtype=np. 1.core.1 numpy._frommethod instance at 0x28207a0> Force the mask to soft. Examples >>> import numpy. 0]]) >>> a = ma. 0].-.int) >>> a[1.--] [0 0 0]]. 0. [0.zeros((3. 0.ma. See Also: 1.ma. 0]. This function is a shortcut to mask_rowcols with axis equal to 0. 1) >>> a masked_array(data = [[0 0 0] [0 -.ma.8.ma.ma as ma >>> a = np. Masked arrays 349 . Release 1.

Release 1. Whether the mask of a masked array is hard or soft is determined by its hardmask property. Continued on next page Chapter 1.unshare_mask() Copy the mask and set the sharedmask flag to False. dtype=bool) >>> x. See Also: sharedmask Conversion operations > to a masked array ma. Array objects . 4]]. See Also: hardmask MaskedArray. A copy of the mask is only made if it was shared. harden_mask sets hardmask to True.harden_mask() Force the mask to hard. dtype. Return input with invalid data masked and replaced by a fill value. order]) ma.shrink_mask() Reduce a mask to nomask when possible.fix_invalid(a[.asanyarray(a[.2 ]. fill_value]) 350 Convert the input to a masked array of the given data-type. [False. Parameters None Returns None Examples >>> x = np. mask. False]].NumPy Reference.ma. soften_mask sets hardmask to False.8.mask False MaskedArray.shrink_mask() >>> x.soften_mask() Force the mask to soft. False]. conserving subclasses. Whether the mask of a masked array is hard or soft is determined by its hardmask property. Whether the mask is shared between masked arrays can be seen from the sharedmask property. Convert the input to a masked array.array([[1.1 hardmask MaskedArray. mask=[0]*4) >>> x. dtype]) ma. [3. See Also: hardmask MaskedArray. copy. unshare_mask ensures the mask is not shared.asarray(a[.mask array([[False.

]. tuples. copy]) Mask an array where equal to a given value.asarray(x) masked_array(data = [[ 0.arange(10. . copy]) Mask an array where less than a given value. fill_value = 1e+20) 1. 8. 9. copy]) Mask an array inside a given interval. ma. copy]) Mask an array where a condition is met. value[. Examples >>> x = np. in any form that can be converted to a masked array.asarray(a. value[. [ 5. but conserves subclasses.masked_greater_equal(x. This includes lists. 9. ma. v1. 4. Parameters a : array_like Input data.masked_values(x... copy. lists of tuples. Returns out : MaskedArray Masked array interpretation of a. ma. 2.masked_less_equal(x.. ma.masked_outside(x. value[. 6. 3. 7.]]) >>> np. 4. ma. If a is a subclass of MaskedArray. 6. a base class MaskedArray is returned. See Also: asanyarray Similar to asarray. optional Whether to use row-major (‘C’) or column-major (‘FORTRAN’) memory representation.ma. value[. Masked arrays 351 .. 3. ma. ma. No copy is performed if the input is already an ndarray. order=None) Convert the input to a masked array of the given data-type.. the data-type is inferred from the input data.reshape(2.masked_object(x. dtype=None. 8.]) Mask using floating point equality.ma.NumPy Reference. order : {‘C’. shrink]) Mask the array x where the data are exactly equal to value. dtype : dtype. v1. numpy.masked_not_equal(x. value[. Default is ‘C’. mask = False.masked_equal(x. copy]) Mask an array where less than or equal to a given value. copy]) Mask an array where not equal to a given value.8.. copy]) Mask an array where greater than or equal to a given value. copy]) Mask an array outside a given interval. ma.masked_less(x.]]. atol. 1.masked_inside(x.. Release 1. tuples of tuples..] [ 5. 5) >>> x array([[ 0. v2[. a[. ‘F’}. copy]) Mask an array where invalid values occur (NaNs or infs). 7. ma. rtol.masked_greater(x. ma.90 – continued from previous page ma. value[. v2[. ma. value[.masked_invalid(a[.masked_where(condition..7. optional By default. ndarrays and masked arrays.1 Table 1.). 1. copy]) Mask an array where greater than a given value. 2. tuples of lists.. value[.

].asanyarray(x) masked_array(data = [[ 0.MaskedArray’> numpy... its class is conserved. 7. 352 Chapter 1. fill_value = 1e+20) >>> type(np. 6. 8. 2. fill_value=None) Return input with invalid data masked and replaced by a fill value. Examples >>> x = np.]]. order : {‘C’. 4. 5) >>> x array([[ 0.ma.core. inf.ma. the data-type is inferred from the input data. 6.8. 4.asanyarray(x)) <class ’numpy. 1.fix_invalid(a.]]) >>> np. optional By default. a (subclass of) ndarray. Default is ‘C’. Release 1. 2. 9.. 7. 1..asanyarray(a.1 >>> type(np. Default is True. ‘F’}.ma. optional Whether to use row-major (‘C’) or column-major (‘FORTRAN’) memory representation.] [ 5.arange(10.ma. 9.ma. but does not conserve subclass. optional Whether to use a copy of a (True) or to fix a in place (False).. mask=False.NumPy Reference.core. 3. in any form that can be converted to an array. No copy is performed if the input is already an ndarray.. Array objects .).ma.asarray(x)) <class ’numpy. mask = False.reshape(2.. conserving subclasses. Invalid data means values of nan. Returns out : MaskedArray MaskedArray interpretation of a. If a is a subclass of MaskedArray. 8. etc.MaskedArray’> numpy. 3. dtype : dtype. Parameters a : array_like Input array. copy : bool. See Also: asarray Similar to asanyarray.. copy=True.ma. Parameters a : array_like Input data. [ 5. dtype=None) Convert the input to a masked array.

Masked arrays 353 .fix_invalid(x) masked_array(data = [-. Notes A copy is performed by default. mask=[1] + [0]*3) >>> x masked_array(data = [-.--].1 fill_value : scalar.fill_value is used.00000000e+00.0 -. For floating point arrays.fix_invalid(x) >>> fixed. 1. This function is a shortcut to masked_where.masked_greater(x.nan. fill_value = 1e+20) >>> fixed = np.00000000e+00..-1. np. Default is None.8. -1. NaN.masked_equal(a. -1. value. value). optional Value used for fixing invalid data. masked_values Mask using floating point equality. Inf]) 1.ma as ma >>> a = np. 2. consider using masked_values(x.00000000e+20]) >>> x. copy=True) Mask an array where equal to a given value. fill_value = 1e+20) >>> np.7. in which case the a. See Also: masked_where Mask where a condition is met.data array([ 1. Release 1.masked_equal(x.data array([ 1.ma.3]. -1. 3]) >>> ma. fill_value=999999) numpy.ma.. copy=True) Mask an array where greater than a given value.ma. Examples >>> import numpy. value. Returns b : MaskedArray The input array with invalid entries fixed.-1. np. 1..array([1.inf]. with condition = (x == value). 2) masked_array(data = [0 1 -. numpy. Examples >>> x = np.00000000e+20. mask = [ True False True True]. mask = [ True False False False].NumPy Reference. mask = [False False True False].ma.0 nan inf]. 1.ma.arange(4) >>> a array([0.

Array objects . mask = [False False True True].ma. v2. 0. 1. 354 Chapter 1. fill_value=999999) numpy. 0.31. 2.masked_inside(x. 3]) >>> ma. Notes The array x is prefilled with its filling value.ma as ma >>> x = [0. value.8.masked_greater_equal(x. numpy. See Also: masked_where Mask where a condition is met.4. with condition = (x > value).1 This function is a shortcut to masked_where. The boundaries v1 and v2 can be given in either order. Shortcut to masked_where.3) masked_array(data = [0.masked_greater(a.01. with condition = (x >= value).3.2 -. where condition is True for x inside the interval [v1. 2) masked_array(data = [0 1 -. 1. 0. 2. Examples >>> import numpy.masked_inside(x.1].NumPy Reference.2. 3]) >>> ma. Release 1.ma as ma >>> a = np.1] >>> ma.ma.-0. 2) masked_array(data = [0 1 2 --]. See Also: masked_where Mask where a condition is met.31 1. -1. See Also: masked_where Mask where a condition is met.2. copy=True) Mask an array inside a given interval. -0.arange(4) >>> a array([0. Examples >>> import numpy.v2] (v1 <= x <= v2). This function is a shortcut to masked_where.masked_greater_equal(a.--].arange(4) >>> a array([0.ma as ma >>> a = np.-. v1. Examples >>> import numpy. 1. -0. copy=True) Mask an array where greater than or equal to a given value. mask = [False False False fill_value=999999) True].4 -1.

1 mask = [False False fill_value=1e+20) True True False False].arange(4) >>> a array([0.. mask = [False False True True False]. Masked arrays 355 . This function is a shortcut to masked_where.2 -.]) >>> ma.7. dtype=np.NaN >>> a[3] = np. fill_value=999999) numpy.-.4.ma as ma >>> a = np.31 1.masked_less_equal(x.masked_less(x.8.arange(5. 1.. fill_value=1e+20) numpy. Inf. The order of v1 and v2 doesn’t matter.ma. with condition = (x <= value). value.4 -1. 1. Examples >>> import numpy.0]. Any pre-existing mask is conserved. 0. mask = [False False True True False False].masked_invalid(a. Only applies to arrays with a dtype where NaNs or infs make sense (i.0 -.-0. fill_value=1e+20) numpy.PINF >>> a array([ 0. 1.ma. value. mask = [ True True False False]. -0. but accepts any array_like object. See Also: masked_where Mask where a condition is met. floating point types). See Also: masked_where Mask where a condition is met. 4. Release 1.masked_inside(x.3. 2) masked_array(data = [-.masked_less(a. NaN. copy=True) Mask an array where less than a given value. >>> ma.2 3].ma as ma >>> a = np.3) masked_array(data = [0.0 1. Examples >>> import numpy.e. with condition = ~(np.masked_invalid(a) masked_array(data = [0.-. copy=True) Mask an array where less than or equal to a given value. 3]) >>> ma.-. 2.float) >>> a[2] = np.NumPy Reference.isfinite(a)). with condition = (x < value). This function is a shortcut to masked_where. copy=True) Mask an array where invalid values occur (NaNs or infs).1].ma. This function is a shortcut to masked_where.

masked_not_equal(a. shrink=True) Mask the array x where the data are exactly equal to value. 2) masked_array(data = [-. shrink : {True. with condition = (x != value).ma as ma >>> a = np. Release 1.masked_less_equal(a.ma. optional Whether to collapse a mask full of False to nomask Returns result : MaskedArray 356 Chapter 1. fill_value=999999) numpy.3]. 3]) >>> ma. fill_value=999999) numpy. See Also: masked_where Mask where a condition is met. 2. copy=True) Mask an array where not equal to a given value. Array objects . This function is a shortcut to masked_where.ma.ma as ma >>> a = np. copy=True.masked_object(x. value. optional Whether to return a copy of x. 2) masked_array(data = [-. This function is similar to masked_values. Parameters x : array_like Array to mask value : object Comparison value copy : {True. use masked_values instead. 1.arange(4) >>> a array([0.arange(4) >>> a array([0. Examples >>> import numpy. mask = [ True True False True]. value.8. 3]) >>> ma.-.NumPy Reference. but only suitable for object arrays: for floating point. 2. mask = [ True True True False]. False}.-.masked_not_equal(x.-. False}. Examples >>> import numpy.1 See Also: masked_where Mask where a condition is met.2 --]. 1.

0.masked_object(fresh_food.v2] (x < v1)|(x > v2). v2.ma as ma >>> x = [0. ’green_eggs’) >>> print eat [cheese ham pineapple] Note that mask is set to nomask if possible. 0.array([’cheese’. -1.0. mask = False. Examples >>> import numpy. ’green_eggs’) >>> print eat [-.7.masked_outside(x.masked_outside(x. dtype=object) >>> # don’t eat spoiled food >>> eat = ma. 1.--].01 0. mask = [ True True False False True fill_value=1e+20) True].2 -.3.8.3) masked_array(data = [-. copy=True) Mask an array outside a given interval. fill_value=?) numpy. Shortcut to masked_where.-. The order of v1 and v2 doesn’t matter. See Also: masked_where Mask where a condition is met. where condition is True for x outside the interval [v1. v1.masked_object(food.01. masked_equal Mask where equal to a given value (integers).2. 0. See Also: masked_where Mask where a condition is met. Masked arrays 357 .1 The result of masking x where equal to value. ’ham’.1] >>> ma. 1. Notes The array x is prefilled with its filling value. ’ham’]. >>> eat masked_array(data = [cheese ham pineapple]. masked_values Mask using floating point equality.31. The boundaries v1 and v2 can be given in either order. Examples >>> import numpy.NumPy Reference. ’pineapple’].4. -0. -0. dtype=object) >>> eat = ma.array([’green_eggs’. Release 1.ma as ma >>> food = np.ma.2.ham] >>> # plain ol‘ ham is boring >>> fresh_food = np.

0 -.0. value : float Masking value. rtol : float.value) <= atol+rtol*abs(value)) The fill_value is set to value and the mask is set to nomask if possible.masked_outside(x.3.01 0.masked_values(x.-. 358 Chapter 1. mask = [False True False True False].e. 1. 3]) >>> ma.--].2. Release 1.NumPy Reference.3) masked_array(data = [-. optional Tolerance parameter (1e-8). 2.3.1.1) masked_array(data = [1.2 -. optional Whether to collapse a mask full of False to nomask. Returns result : MaskedArray The result of masking x where approximately equal to value.ma.1) Note that mask is set to nomask if possible. value. copy=True. where the following condition is True (abs(x . Parameters x : array_like Array to mask. fill_value=1. mask = [ True True False False True fill_value=1e+20) True].1. optional Whether to return a copy of x. i.masked_values(x. Return a MaskedArray. Examples >>> import numpy. -0. 1. For integers.array([1.0]. 1. masked_equal Mask where equal to a given value (integers).ma as ma >>> x = np. consider using masked_equal.0 -. rtol=1e-05. masked where the data in array x are approximately equal to value. optional Tolerance parameter. 0. numpy. Array objects .1 >>> ma. shrink=True) Mask using floating point equality.8. shrink : bool. atol=1e-08. atol : float. copy : bool. See Also: masked_where Mask where a condition is met.

2) masked_array(data = [0 1 -. copy : bool If True (default) make a copy of a in the result. 1. ]. fill_value=999999) numpy. Returns result : MaskedArray The result of masking a where condition is True. a. For integers. 4]) >>> ma. mask = [False False True False False]. 1.8. consider using masked_values instead. Return a as an array masked where condition is True.7. fill_value=1.5) 2. masked_greater_equal Mask where greater than or equal to a given value.3 4].3 4]. 3.NumPy Reference. Any masked values of a or condition are also masked in the output. mask = [False False True False False]. 1. When condition tests floating point values for equality. a : array_like Array to mask.masked_values(x. If False modify a in place and return a view.5) masked_array(data = [ 1. the fill value will be different in general to the result of masked_equal. Parameters condition : array_like Masking condition. 2) masked_array(data = [0 1 -. masked_equal Mask where equal to a given value.ma. masked_less_equal Mask where less than or equal to a given value. fill_value=2) >>> ma.masked_where(condition.masked_values(x. 2. See Also: masked_values Mask using floating point equality. >>> x = np. copy=True) Mask an array where a condition is met.masked_equal(x.1 3.1 mask = False.1 >>> ma. Release 1. 1. Masked arrays 359 . masked_not_equal Mask where not equal to a given value.arange(5) >>> x array([0. 1.

1 masked_less Mask where less than a given value.NumPy Reference. mask = [ True True True False]. 1. b) masked_array(data = [a b -.3]. masked_inside Mask inside a given interval. ’c’. >>> c = ma. mask = [False False True False].3].-. Examples >>> import numpy.masked_where(a <= 2. >>> b = [’a’.-. masked_outside Mask outside a given interval. 3]) >>> c = ma. Release 1.-. 1. 1. ’d’] >>> ma. fill_value=999999) >>> a array([99. 3]) >>> ma.masked_where(a <= 2.masked_where(a == 2.-. masked_greater Mask where greater than a given value. a) >>> c masked_array(data = [-. Array objects .3]. fill_value=999999) >>> c[0] = 99 >>> c masked_array(data = [99 -. a) masked_array(data = [-.ma as ma >>> a = np. 2. 2.-. copy=False) >>> c[0] = 99 >>> c masked_array(data = [99 -. fill_value=999999) Mask array b conditional on a.d]. mask = [ True True True False].8. 2. fill_value=N/A) Effect of the copy argument. masked_invalid Mask invalid values (NaNs or infs).masked_where(a <= 2.arange(4) >>> a array([0.3]. a. 3]) When condition or a contain masked values.-. 360 Chapter 1. fill_value=999999) >>> a array([0. mask = [False True True False]. ’b’. mask = [False True True False].

Release 1. b) >>> b masked_array(data = [-.compressed() ma.3].1 >>> a = np. both rows and columns are suppressed.MaskedArray.MaskedArray. •If axis is 1 or -1. Returns compressed_array : ndarray The compressed array. Default is None.ma. 1. Parameters axis : int. with masked values filled with a given value. b) masked_array(data = [-.masked_where(b == 0. •If axis is None. Suppress the rows and/or columns of a 2-D array that contain Suppress whole rows of a 2-D array that contain masked values.masked_where(a == 3. mask = [ True False True True]. Return input as an array with masked data replaced by a fill value.masked_where(a == 2.compress_cols(a) Suppress whole columns of a 2-D array that contain masked values. fill_value=999999) >>> b = np.compress_rowcols(x.NumPy Reference. fill_value=999999) > to a ndarray ma. only rows are suppressed. mask = [False False True False]. a) >>> a masked_array(data = [0 1 -.arange(4) >>> a = ma.arange(4) >>> b = ma. 1). only columns are suppressed.compressed(x) ma. Return all the non-masked data as a 1-D array.filled(a[.8. extras. Return all the non-masked data as a 1-D array.compress_rowcols numpy. The suppression behavior is selected with the axis parameter. Return a copy of self. axis]) ma. numpy.compress_rowcols(x[.extras. fill_value]) ma. fill_value=999999) >>> ma.ma.7.compress_rowcols(a. axis=None) Suppress the rows and/or columns of a 2-D array that contain masked values.compress_rows(a) ma.--]. mask = [ True False False False].1 2 3]. optional Axis along which to perform the operation.filled([fill_value]) Suppress whole columns of a 2-D array that contain masked values.compress_rowcols for details. Masked arrays 361 .compress_cols(a) ma.1 -. see See Also: extras. This is equivalent to np. •If axis is 0.ma.

Release 1. mask = [[ True False False] [ True False False] [False False False]]..ma.compress_rows(a) Suppress whole rows of a 2-D array that contain masked values.compress_rowcols numpy. 0.fill_value.compressed Equivalent method. 7.ma. 8]]) >>> np. 5].filled(a. fill_value=None) Return input as an array with masked data replaced by a fill value. 0]. [4.compressed for details. fill_value = 999999) >>> np. . Parameters a : MaskedArray or array_like An input object.compress_rowcols(x. 0]]) >>> x masked_array(data = [[-.compress_rowcols(a. Default is None. 0].ma.compress_rowcols(x) array([[7. extras.compressed(x) Return all the non-masked data as a 1-D array. mask=[[1.8.compress_rowcols for details. 3).extras.compress_rowcols(x..ma. If a is not a MaskedArray.1 Examples >>> x = np.arange(9). see See Also: MaskedArray. This function is equivalent to calling the “compressed” method of a MaskedArray.. 0. Array objects .NumPy Reference.ma.1 2] [-.4 5] [6 7 8]].ma. optional Filling value.. If a is a MaskedArray and fill_value is None. fill_value : scalar. 0) array([[6. 8]]) >>> np. [1. numpy.ma. 0. This is equivalent to np.array(np.extras.ma.reshape(3. see See Also: extras.extras. fill_value is set to a. MaskedArray. 0). 1) array([[1. 8]]) numpy.extras. . 2]. a itself is returned. [7. 362 Chapter 1. [0.

Notes The result is not a MaskedArray! Examples 1.array(np. ..NumPy Reference. Returns filled_array : ndarray A copy of self with invalid entries replaced by fill_value (be it the function argument or the attribute of self. Release 1.array(np. 7. mask=[[1.ma. 0. [0. 4.arange(9). mask=[0]*2 + [1]*3) >>> x. [999999. 5].. with masked values filled with a given value.filled(fill_value=None) Return a copy of self.compressed()) <type ’numpy. optional The value to use for invalid entries (None by default). If None. [1. 2].ndarray’> MaskedArray.arange(5). 0]]) >>> x.. Parameters fill_value : scalar. 0]. 8]]) MaskedArray. 1]) >>> type(x.1 Returns a : ndarray The filled array.reshape(3. Masked arrays 363 . the fill_value attribute of the array is used instead.compressed() array([0. 3).7.filled() array([[999999. [ 6. . Returns data : ndarray A new ndarray holding the non-masked data is returned.compressed() Return all the non-masked data as a 1-D array.ma. 0.8. 0. 0]. 1. See Also: compressed Examples >>> x = np.. Notes The result is not a MaskedArray! Examples >>> x = np.

5]. -999. [7. 4]]) > to another object ma.filled()) <type ’numpy. None.3]. Raises NotImplementedError When tofile is called. sep.2. -999.9]].tolist() [[1. 5. None].ma.ma. filled returns a matrix: >>> x = np. [7. Array objects . Default is None. Masked values are converted to fill_value. 2]. Transforms a masked array into a flexible-type array. -999].8.array([1.5. 9]] MaskedArray. The flexible type array that is returned will have two fields: 364 Chapter 1.8.0.array([[1. 3].3. 3]. MaskedArray. format=’%s’) Save a masked array to a file in binary format. Return the data portion of the masked array as a hierarchical Python list.matrix([[1.2. [4. the corresponding entries in the output list will be None. Examples >>> x = np. [None.tolist(-999) [[1. Data items are converted to the nearest compatible Python type. This means that if the data part of the masked array is a matrix.filled() matrix([[ 1.ma. optional The value to use for invalid entries.6].tostring([fill_value. 4.MaskedArray. 0]]) >>> x. [999999. 2.filled() array([1.ndarray’> Subclassing is preserved.NumPy Reference. sep=’‘. None. [7. format]) ma. order]) Save a masked array to a file in binary format. mask=[0.1 >>> x = np.MaskedArray.tolist(fill_value=None) Return the data portion of the masked array as a hierarchical Python list. fill_value=-999) >>> x. 999999].tofile(fid[.tolist([fill_value]) ma.torecords() ma.0]*4) >>> x.1. If fill_value is None. 1]. mask=[[0.1]. Release 1. -999.MaskedArray.array(np. Return the array data as a string containing the raw bytes in the array. [-999. MaskedArray.torecords() Transforms a masked array into a flexible-type array. Parameters fill_value : scalar. 5. 4]]). -999]) >>> type(x.0.tofile(fid. Returns result : list The Python list representation of the masked array.MaskedArray. [3. 9]] >>> x.4. [1. mask=[0] + [1. Warning: This function is not implemented yet.

Parameters None Returns record : ndarray A new flexible-type ndarray with two fields: the first element containing a value. The returned record shape matches self.8. optional Value used to fill in the masked values.9]].tostring.3].1 •the _data field stores the _data part of the array.[4. • ‘C’ – C order (row major).6].. • ‘F’ – Fortran order (column major). tofile Notes As for ndarray.NumPy Reference. False) (6.tostring. True) (5. •the _mask field stores the _mask part of the array.’A’}.) will be lost.. Default is ‘C’. tolist. See Also: ndarray.tostring(fill_value=None. Notes A side-effect of transforming a masked array into a flexible ndarray is that meta information (fill_value. False)] [(4.7. optional Order of the data item in the copy. False)]] MaskedArray.’F’.ma.toflex() [[(1.8. current order of array. True) (3. Release 1. The array is filled with a fill value before the string conversion. information about the shape.2.3] [-. in which case order : {‘C’.[7.shape. False) (8. etc. Parameters fill_value : scalar. • ‘A’ – Any.fill_value is used..9]] >>> print x.5. mask=[0] + [1. 1.array([[1. MaskedArray. Examples >>> x = np. order=’C’) Return the array data as a string containing the raw bytes in the array. True)] [(7. True) (9. will be lost. False) (2. Masked arrays 365 .5 --] [7 -.0]*4) >>> print x [[1 -. but also about fill_value. Deafult is None. . the second element containing the corresponding mask boolean. • None – Same as ‘A’. dtype.

mask=[[0.dump(a. 0]]) >>> x. See Also: dump Pickle an array Notes This is different from numpy. F : str or file-like object The file to pickle a to. numpy. This is a wrapper around cPickle.load(F) ma. [3.loads(strg) Pickle a masked array to a file.dumps(a) Return a string corresponding to the pickling of a masked array.load which accepts either a file-like object or a filename.dump. Parameters F : str or file The file or file name to load. Array objects .ma. numpy. 4]]). which does not use cPickle but loads the NumPy binary . Parameters a : MaskedArray The array to be pickled.loads(strg) Load a pickle from the current string. numpy. F) ma. 2]. numpy.load which accepts either a file-like object Load a pickle from the current string.loads(strg) is returned. Parameters strg : str 366 Chapter 1.ma.dumps. This is a wrapper around cPickle.8. Wrapper around cPickle.array([[1.ma.1 Examples >>> x = np.array(np. F) Pickle a masked array to a file. Parameters a : MaskedArray The array for which the string representation of the pickle is returned.npy format. Return a string corresponding to the pickling of a masked array.dump(a.ma. [1.tostring() ’\x01\x00\x00\x00?B\x0f\x00?B\x0f\x00\x04\x00\x00\x00’ Pickling and unpickling ma. the full path to the file.NumPy Reference.load(F) Wrapper around cPickle. If a string.dumps(a) ma.ma. The result of cPickle. 1]. Release 1.load.

fill_value == b. 1. Examples >>> x = np.e20 1.].ma. Return the minimum value that can be represented by the dtype of an object.default_fill_value(obj) Return the default fill value for the argument object. return the fill value. b : MaskedArray The masked arrays for which to compare fill values.fill_value. Returns fill_value : scalar or None The common fill value. b) ma.MaskedArray.0 numpy. y) 3. Filling value.7.array([0.default_fill_value(obj) ma.maximum_fill_value(obj) ma.1 The string to load. If a.set_fill_value(a.ma.ma. Filling a masked array ma. Parameters a. fill_value) ma. if any. otherwise return None.fill_value Return the common filling value of two masked arrays. fill_value=3) >>> np.ma. Set the filling value of a.NumPy Reference.]. fill_value=3) >>> y = np. Set the filling value of the masked array.8.set_fill_value([value]) ma. Return the filling value of the masked array.common_fill_value(a. if a is a masked array.ma. numpy.get_fill_value() ma. Release 1. b) Return the common filling value of two masked arrays. See Also: dumps Return a string corresponding to the pickling of a masked array.maximum_fill_value(obj) ma. Masked arrays 367 .MaskedArray.e20+0j ‘?’ ‘N/A’ Parameters obj : ndarray.common_fill_value(a. 1.array([0. or None. Return the minimum value that can be represented by the dtype of an object. if any.MaskedArray.common_fill_value(x. dtype or scalar The array data-type or scalar for which the default fill value is returned. The default filling value depends on the datatype of the input array or the type of the input scalar: datatype bool int float complex object string default True 999999 1. 1. Return the default fill value for the argument object.

This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Array objects .fill_value Return current fill value.int8() >>> ma.NumPy Reference. >>> a = np. 3]. 2. dtype=np.ma.dtype(complex)) (1e+20+0j) numpy.default_fill_value(1) 999999 >>> np. Release 1.int8) >>> ma.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. MaskedArray.array([1.maximum_fill_value(obj) Return the minimum value that can be represented by the dtype of an object. Examples >>> import numpy. Examples >>> np.1. 2.ma.int32() >>> ma.array([1.float32) 368 Chapter 1.default_fill_value(np. set_fill_value Set the filling value of a masked array.array([1. np. dtype} An object that can be queried for it’s numeric type.1 Returns fill_value : scalar The default fill value.8.ma. Returns val : scalar The minimum representable value.. Parameters obj : {ndarray. 2.maximum_fill_value(a) -128 >>> a = np.ma.default_fill_value(np. dtype=np. 3]. Raises TypeError If obj isn’t a suitable numeric type. See Also: minimum_fill_value The inverse function.ma as ma >>> a = np.maximum_fill_value(a) -128 >>> a = np.pi])) 1e+20 >>> np.

dtype=np. the function returns silently.array([1.float32) >>> ma.NumPy Reference.int8() >>> ma.maximum_fill_value(a) -128 >>> a = np. fill_value) Set the filling value of a. If a is not a masked array.maximum_fill_value(a) -inf numpy. This function changes the fill value of the masked array a in place. Release 1. Raises TypeError If obj isn’t a suitable numeric type.7. if a is a masked array.maximum_fill_value(a) -128 >>> a = np.ma.maximum_fill_value(a) -inf numpy. 1. 2.fill_value Return current fill value. This function is useful for calculating a fill value suitable for taking the maximum of an array with a given dtype. Returns val : scalar The minimum representable value.array([1. See Also: minimum_fill_value The inverse function.int32() >>> ma. dtype=np.int8) >>> ma. dtype} An object that can be queried for it’s numeric type. 2. 3].ma. Examples >>> import numpy.ma as ma >>> a = np.maximum_fill_value(obj) Return the minimum value that can be represented by the dtype of an object. MaskedArray. without doing anything. Parameters obj : {ndarray.8.maximum_fill_value(a) -2147483648 An array of numeric data can also be passed. Masked arrays 369 .set_fill_value(a. >>> a = np. Parameters a : array_like Input array. set_fill_value Set the filling value of a masked array. 3].1 >>> ma.

4] >>> a = np. 100) >>> a [0. 4]) MaskedArray.ma as ma >>> a = np.3 4].3 4]. 100) >>> a array([0. -999) >>> a masked_array(data = [-. Array objects . 1.set_fill_value Equivalent method. 3.fill_value Return current fill value. 1.get_fill_value() Return the filling value of the masked array.1 fill_value : dtype Filling value.-. A consistency test is performed to make sure the value is compatible with the dtype of a. 3. 2. 1. Returns fill_value : scalar The filling value. fill_value=999999) >>> ma. fill_value=-999) Nothing happens if a is not a masked array. 3. >>> a = range(5) >>> a [0.set_fill_value(a. 2.arange(5) >>> a array([0. mask = [ True True True False False].masked_where(a < 3.-. MaskedArray.arange(5) >>> a array([0. Returns None Nothing returned by this function. 2. 1. 1.set_fill_value(a. 3. 4]) >>> a = ma. mask = [ True True True False False]. 4]) >>> ma. MaskedArray. See Also: maximum_fill_value Return the default fill value for a dtype.8.-. 370 Chapter 1.-. 4] >>> ma.NumPy Reference. 3. 2. Examples >>> import numpy. 2.set_fill_value(a. a) >>> a masked_array(data = [-. Release 1.

get_fill_value() -inf MaskedArray. Masked arrays Compute the anomalies (deviations from the arithmetic mean) along the given a Compute the anomalies (deviations from the arithmetic mean) along the given a Return the weighted average of array over the given axis.int32.ma.1 Examples >>> for dt in [np.fill_value -inf >>> x. rowvar. fill_value=-np. fill_value=-np. axis. dtype]) ma.anomalies(self[.inf) >>> x. np.conjugate(x[. See Also: ma.anom(self[. optional The new filling value. y.inf) >>> x.8.get_fill_value() ..fill_value 1e+20 MaskedArray. Release 1. dtype]) ma.pi) >>> x.ma.array([0. Return correlation coefficients of the input array.fill_value 3. axis.NumPy Reference.array([0.7. weights.1415926535897931 Reset to default: >>> x. 1.ma.set_fill_value() >>> x.set_fill_value(value=None) Set the filling value of the masked array. Parameters value : scalar.. in which case a default based on the data type is used. 1. 1]. bias. np.].. .fill_value Filling value. dtype=dt). np. 999999 999999 1e+20 (1e+20+0j) >>> x = np.]..array([0. returned]) ma.float64. Examples >>> x = np. Default is None.set_fill_value(np.. axis.corrcoef(x[. element-wise..]) 1. np.int64.average(a[.set_fill_value Equivalent function. Return the complex conjugate. Continued on next p 371 .complex128]: . Masked arrays arithmetics Arithmetics ma. out]) ma.

median(a[. axis. axis. ma. 0. ma.MaskedArray. dtype=None) = <numpy. Returns an array of anomalies. 372 Chapter 1. dtype.mean(self[. axis. dtype. For arrays of integer type the default is float32.core.prod(self[. out.anom() masked_array(data = [-1.array([1. dtype. b[. with the same shape as the input and where the arithmetic mean is computed along the given axis. overwrite_input]) Compute the median along the specified axis.cumsum([axis.ma. axis.ma. out. Array objects . ma. optional Axis over which the anomalies are taken.ma.MaskedArray. ma. out]) Returns the average of the array elements. dtype. axis. optional Type to use in computing the variance. mask = False. See Also: mean Compute the mean of the array. out]) Return the sum of the array elements over the given axis. out]) Return the cumulative sum of the elements along the given axis. dtype. ma. allow_masked.MaskedArray. numpy. with the same shape as the input and where the arithmetic mean is computed along the given axis. out]) Return the cumulative product of the elements along the given axis.sum(self[.]. ma. for arrays of float types it is the same as the array type. y. Parameters axis : int. dtype. dtype. dtype. Examples >>> a = np.anom([axis. out]) Return the sum of the array elements over the given axis. bias. out.var([axis. ma. out]) Return the product of the array elements over the given axis.anom(self. dtype.MaskedArray. Release 1. dtype.NumPy Reference. out]) Return the cumulative sum of the elements along the given axis. ddof]) Compute the variance along the specified axis.mean([axis. ddof]) Estimate the covariance matrix. axis. ma.MaskedArray. ma.1 Table 1.std([axis._frommethod instance at 0x2819f38> Compute the anomalies (deviations from the arithmetic mean) along the given axis. dtype. dtype. ma.anomalies(self.3]) >>> a.ma. ddof]) Compute the variance along the specified axis.cumsum(self[. dtype=None) = <numpy.MaskedArray.core. ma. third]) Returns element-wise base array raised to power from second array. axis=None. Returns an array of anomalies. out. The default is to use the mean of the flattened array as reference. ma._frommethod instance at 0x2819f38> Compute the anomalies (deviations from the arithmetic mean) along the given axis.std(self[.var(self[. axis=None. fill_value = 1e+20) 1.prod([axis. dtype.MaskedArray. dtype. ma. out]) Return the cumulative product of the elements along the given axis. ddof]) Compute the standard deviation along the specified axis. out]) Return the product of the array elements over the given axis. axis.2. dtype : dtype. out]) Returns the average of the array elements.cov(x[. rowvar.ma. ddof]) Compute the standard deviation along the specified axis.power(a.95 – continued from previous page ma. numpy.cumprod([axis. ma.8.cumprod(self[. dtype]) Compute the anomalies (deviations from the arithmetic mean) along the given a ma.sum([axis. axis. out.MaskedArray. ma. ma.

or just the result (False). 0. False. True. For arrays of integer type the default is float32. [sum_of_weights] : (tuple of) scalar or MaskedArray The average along the specified axis.ma. numpy. returned : bool.]. Returns average. returned=False) Return the weighted average of array over the given axis. weights : array_like. dtype : dtype. optional Axis over which the anomalies are taken. 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. The return type is np. Release 1. optional Flag indicating whether a tuple (result. When returned is True. Masked arrays 373 . True]) >>> np. for arrays of float types it is the same as the array type. then all data in a are assumed to have a weight equal to one.. axis : int.7. Masked entries are not taken into account in the computation. 0]) 1. Examples >>> a = np. axis=None.1 Parameters axis : int. The default is to use the mean of the flattened array as reference.ma.25 1. fill_value = 1e+20) 1. return a tuple with the average as the first element and the sum of the weights as the second element. 1. optional The importance that each element has in the computation of the average.NumPy Reference. mask = False.2. mask=[False. 3. 2.array([1. 4. sum_of_weights is of the same type as average.ma.anom() masked_array(data = [-1.average(a. optional Type to use in computing the variance. otherwise it is of the same type as a.float64 if a is of integer type.array([1. weights=[3. If returned. Examples >>> a = np. 0. If weights is complex.8. See Also: mean Compute the mean of the array.ma. The default is to compute the variance of the flattened array.3]) >>> a. the imaginary parts are ignored.average(a. Default is False. weights=None.]. Parameters a : array_like Data to be averaged. sum of weights) should be returned as output (True). optional Axis along which the variance is computed.

rowvar : bool.corrcoef. 3].-0. [ 0.5.).66666666667] numpy. the relationship is transposed: each column represents a variable. sumweights = np. Parameters x : array_like Input value. axis=0. while the rows contain observations. 0. element-wise. This keyword can be overridden by the keyword ddof in numpy versions >= 1.ma. where N is the number of observations given (unbiased estimate). y has the same shape as x. then normalization is by N. Examples >>> np. Each row of x represents a variable. rowvar=True.conjugate(1+2j) (1-2j) >>> x = np.eye(2) + 1j * np. 5. with same dtype as y.-1. with observations in the columns.] [ 4. y=None.corrcoef.] [ 2.8.core. y : array_like. .ma.ma.1 >>> x = np.-0.]] >>> avg. bias=False. Returns y : ndarray The complex conjugate of x.NumPy Reference.eye(2) >>> np. 3. optional If rowvar is True (default). 1.j]]) numpy.66666666667 3. allow_masked=True. 374 Chapter 1.ma. optional Default normalization (False) is by (N-1). bias : bool. Otherwise. and each column a single observation of all those variables. Parameters x : array_like A 1-D or 2-D array containing multiple variables and observations. weights=[1. For more details and examples. see numpy. If bias is 1.j.conjugate(x) array([[ 1. 2) >>> print x [[ 0. out ]) = <numpy. ddof=None) Return correlation coefficients of the input array. returned=True) >>> print avg [2.average(x. 1. The complex conjugate of a complex number is obtained by changing the sign of its imaginary part.ma. Release 1.corrcoef(x.j. 2.conjugate(x[.reshape(3.-1. then each row represents a variable._MaskedUnaryOperation instance at 0x272bfc8> Return the complex conjugate. Also see rowvar below. Array objects .j].arange(6. Except for the handling of missing data this function does the same as numpy.. optional An additional set of variables and observations..

Each row of x represents a variable. By default.cov(x. This keyword can be overridden by the keyword ddof in numpy versions >= 1. with observations in the columns. a common mask is allocated: if x[i. For more details and examples. cov Estimate the covariance matrix. then normalization is by N.1 allow_masked : bool.ma. optional Default normalization (False) is by (N-1). If False. this overrides the value implied by bias. ddof : {None. ddof=None) Estimate the covariance matrix. masked values are propagated pair-wise: if a value is masked in x. then each row represents a variable. rowvar=True.7.8. Except for the handling of missing data this function does the same as numpy. the corresponding value is masked in y. allow_masked : bool. ddof : {None. If False.5.cov. y=None. then y[i. optional If rowvar is True (default). y has the same form as x. optional New in version 1.5. optional If True. optional If True. where N is the number of observations given (unbiased estimate). Release 1.j] is masked. If not None normalization is by (N . Masked arrays 375 . the relationship is transposed: each column represents a variable. where N is the number of observations. bias : bool. see numpy. bias=False. int}. If not None normalization is by (N . the corresponding value is masked in y. raises an exception.NumPy Reference. The default value is None. numpy.ddof).ddof). Parameters x : array_like A 1-D or 2-D array containing multiple variables and observations. optional New in version 1. optional An additional set of variables and observations. 1. masked values are recognized as such. while the rows contain observations. this overrides the value implied by bias. allow_masked=True. where N is the number of observations.j] will also be masked. Otherwise. rowvar : bool. int}. Also see rowvar below. The default value is None.5. masked values are propagated pair-wise: if a value is masked in x.corrcoef Equivalent function in top-level NumPy module. y : array_like. and each column a single observation of all those variables. If bias is True.cov. Setting allow_masked to False will raise an exception if values are missing in either of the input arrays. raises a ValueError exception when some values are missing. See Also: numpy. If x and y have the same shape.

it defaults to the dtype of a. Array objects . axis may be negative. dtype=None._frommethod instance at 0x2820170> Return the cumulative product of the elements along the given axis.0.arange(10). out=None) = <numpy. The cumulative sum is calculated over the flattened array by default.ma.1. out=None) = <numpy. optional Alternative output array in which to place the result. Masked values are set to 1 internally during the computation. the default platform integer is used. Release 1. A new array holding the result is returned unless out is specified.0]) >>> print marr. mask=[0. See Also: numpy. Examples >>> marr = np. dtype}.core. -1.ma. Parameters axis : {None. out : ndarray.0. However. Masked values are set to 0 internally during the computation. optional Type of the returned array and of the accumulator in which the elements are summed. In that case. Notes The mask is lost if out is not a valid MaskedArray ! Arithmetic is modular when using integer types.ma. and no error is raised on overflow. int}. Returns cumsum : ndarray. in which case a reference to out is returned. their position is saved.-. optional 376 Chapter 1. their position is saved. If dtype is not specified. The cumulative product is taken over the flattened array by default.cov numpy. dtype : {None.0.core. and the result will be masked at the same locations. and the result will be masked at the same locations. int}. unless a has an integer dtype with a precision less than that of the default platform integer. -1.1 Raises ValueError Raised if some values are missing and allow_masked is False. optional Axis along which the sum is computed.ma.1. axis=None.array(np.cumsum(self.NumPy Reference. Parameters axis : {None. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. The default (axis = None) is to compute over the flattened array.0.cumsum() [0 1 3 -.-._frommethod instance at 0x2820200> Return the cumulative sum of the elements along the given axis. axis=None. However.9 16 24 33] numpy.0.1. otherwise over the specified axis. in which case it counts from the last to the first axis.ma.8. dtype=None.cumprod(self. otherwise over the specified axis.

optional Alternative output array in which to place the result. optional Determines the type of the returned array and of the accumulator where the elements are multiplied. Refer to numpy. The default is to compute the mean of the flattened array. dtype : {None. For integer inputs. dtype}. out : ndarray. Masked entries are ignored.mean(self. It must have the same shape as the expected output but the type will be cast if necessary. for floating point. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. Release 1. and no error is raised on overflow.mean for the full documentation. The average is taken over the flattened array by default. optional Type to use in computing the mean. otherwise a reference to the output array is returned.ma. returns a new array containing the mean values.7. numpy.mean Equivalent function. the default is float64. optional Alternative output array in which to place the result.1 Axis along which the product is computed. axis=None.core. See Also: numpy. out=None) = <numpy.NumPy Reference. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer. dtype=None. Returns cumprod : ndarray A new array holding the result is returned unless out is specified. The default (axis = None) is to compute over the flattened array. optional Axis along which the means are computed. otherwise over the specified axis. If a is not an array. Masked arrays 377 . 1. a conversion is attempted. Notes The mask is lost if out is not a valid MaskedArray ! Arithmetic is modular when using integer types. dtype : dtype.ma. Returns mean : ndarray.8.ma. then the default platform integer precision is used. Parameters a : array_like Array containing numbers whose mean is desired. the dtype is the same as that of a. out : ndarray. inputs it is the same as the input dtype. Otherwise. see dtype parameter above If out=None._frommethod instance at 0x2820440> Returns the average of the array elements. in which case a reference to out is returned. axis : int.

or {Vs[N/2 . or the input data-type. otherwise. when N is odd. Parameters a : array_like Input array or object that can be converted to an array. optional Alternative output array in which to place the result.mean() 1. Examples >>> a = np.1 numpy. 378 Chapter 1. Release 1. but it will probably be fully or partially sorted.ma. overwrite_input=False) Compute the median along the specified axis. an error will be raised. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. Note that. Returns the median of the array elements. axis : int. This will save memory when you do not need to preserve the contents of the input array.5 numpy.1] + Vs[N/2]}/2 when N is even. Returns median : ndarray A new array holding the result is returned unless out is specified. out : ndarray. and the input is not already an ndarray.NumPy Reference. optional Axis along which the medians are computed. numpy. False.average Weighted average. Treat the input as undefined. then allow use of memory of input array (a) for calculations.median(a. The input array will be modified by the call to median. See Also: mean Notes Given a vector V with N non masked values.mean Equivalent function on non-masked arrays.2. axis=None. the median of V is the middle value of a sorted copy of V (Vs) .i.e.ma. in which case a reference to out is returned. out=None. optional If True. overwrite_input : bool.8. Array objects . The default (None) is to compute the median along a flattened version of the array. mask=[False. fill_value = 999999) >>> a.3].array([1.ma. mask = [False False True]. Vs[(N-1)/2]. Default is False. Return data-type is float64 for integers and floats smaller than float64. if overwrite_input is True. True]) >>> a masked_array(data = [1 2 --].

fill_value = 1e+20) numpy.ma. then the default platform integer precision is used.arange(10).power. out=None) = <numpy.ma.power(a. It must have the same shape as the expected output but the type will be cast if necessary.array(np. Otherwise. This is the masked array version of numpy. out : {None._frommethod instance at 0x2820560> Return the product of the array elements over the given axis.ma.ma. Parameters axis : {None.ma. scalar}. dtype : {None. See Also: prod equivalent function 1.array(np. axis=-1.extras.median(x) 2.power.median(x. b.ma. For details see numpy. see dtype parameter above.median(x) 1. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer.8. mask=[0]*6 + [1]*4) >>> np.5 >>> x = np.extras. Returns a reference to the specified output array if specified. optional Determines the type of the returned array and of the accumulator where the elements are multiplied.prod(self. third=None) Returns element-wise base array raised to power from second array. array}. mask = False. optional Alternative output array in which to place the result. Returns a 0d array when a is 1d or axis=None.ma.5 >>> np.extras. third has to be None. Release 1.power is not supported.arange(8).power Notes The out argument to numpy.1 Examples >>> x = np. optional Axis over which the product is taken.]. dtype=None. numpy.ma. dtype}. See Also: numpy. If None is used. Masked arrays 379 . Returns an array whose shape is the same as a with the specified axis removed. 5. Returns product_along_axis : {array. Masked elements are set to 1 internally for computation. the dtype is the same as that of a. overwrite_input=True) masked_array(data = [ 2.7. 5). then the product is over all the array elements. axis=None.core. mask=[0]*4 + [1]*4) >>> np.NumPy Reference.reshape(2. int}.

The standard deviation is computed for the flattened array by default. ddof : int.NumPy Reference. axis=1) array([ 2.]) numpy... optional Means Delta Degrees of Freedom. the result will broadcast correctly against the original arr.]]) 24. dtype : dtype. ddof=0) = <numpy. the axes which are reduced are left in the result as dimensions with size one.2. keepdims : bool. Examples >>> np.doc. return a new array containing the standard deviation. With this option.0 >>> np.]. see dtype parameter above. Release 1. otherwise over the specified axis. optional Axis along which the standard deviation is computed. nanmean. Returns the standard deviation. dtype=np. mean.ddof. and no error is raised on overflow.. Parameters a : array_like Calculate the standard deviation of these values. It must have the same shape as the expected output but the type (of the calculated values) will be cast if necessary.[3.0 >>> np.]) 2. nanvar numpy. Returns standard_deviation : ndarray. The default is to compute the standard deviation of the flattened array. If out is None. By default ddof is zero. Array objects .2. dtype=None. axis : int.ma.prod([[1. for arrays of float types it is the same as the array type.2.4. out : ndarray.ufuncs Section “Output arguments” 380 Chapter 1. The divisor used in calculations is N . where N represents the number of elements. a measure of the spread of a distribution. out=None.8.prod([1. axis=None. of the array elements.core.[3.2.. 12.].]._frommethod instance at 0x2820878> Compute the standard deviation along the specified axis. For arrays of integer type the default is float64. optional Alternative output array in which to place the result.1 Notes Arithmetic is modular when using integer types. optional If this is set to True.int32) 2 >>> np.]].prod([[1. See Also: var.. nanstd..4.ma. otherwise return a reference to the output array..std(self.prod([1. optional Type to use in computing the standard deviation.

[3. ddof is specified.float32) >>> a[0.5]) In single precision.NumPy Reference. Note that.]) >>> np.8..float64) 0. so that the result is always real and nonnegative. Depending on the input data. If. 0.5.x.1 Notes The standard deviation is the square root of the average of the squared deviations from the mean. The average squared deviation is normally calculated as x. dtype=None. If dtype has the value None and the type of a is an integer type of precision less than the default platform integer. axis=0) array([ 1. Examples >>> a = np. std() can be inaccurate: >>> a = np. 1. then the default platform integer precision is used.sum(self.1180339887498949 >>> np. axis=None. int}.array([[1.ddof is used instead. Parameters axis : {None. -1.zeros((2. Masked elements are set to 0 internally.ma.mean())**2)). it will not be an unbiased estimate of the standard deviation per se. axis=1) array([ 0. however. optional 1. Otherwise. out=None) = <numpy. 4]]) >>> np.std(a. the divisor N . dtype=np. 2]. the dtype is the same as that of a.ma. Masked arrays 381 . dtype : {None. optional Determines the type of the returned array and of the accumulator where the elements are summed. optional Axis along which the sum is computed. for complex numbers.std(a. dtype=np. std takes the absolute value before squaring. especially for float32 (see example below). the std is computed using the same precision the input has. The default (axis = None) is to compute over the flattened array. so even with ddof=1. Specifying a higheraccuracy accumulator using the dtype keyword can alleviate this issue. dtype}.std(a) 0. ndarray}.1 >>> np. out : {None._frommethod instance at 0x2820908> Return the sum of the array elements over the given axis.e. i.std(a..:] = 1. Release 1. this can cause the results to be inaccurate.45172946707416706 Computing the standard deviation in float64 is more accurate: >>> np. The standard deviation computed in this function is the square root of the estimated variance.core.44999999925552653 numpy. For floating-point input.sum() / N.7. ddof=1 provides an unbiased estimator of the variance of the infinite population.:] = 0.512*512). std = sqrt(mean(abs(x . ddof=0 provides a maximum likelihood estimate of the variance for normally distributed variables. where N = len(x).std(a) 1.0 >>> a[1. In standard statistical practice.

dtype=np. optional “Delta Degrees of Freedom”: the divisor used in the calculation is N . If an output array is specified. otherwise over the specified axis.2. Examples >>> x = np. for arrays of float types it is the same as the array type. 382 Chapter 1. where N represents the number of elements. Returns sum_along_axis : MaskedArray or scalar An array with the same shape as self. a conversion is attempted.var(self.8. dtype : data-type. keepdims : bool.1 Alternative output array in which to place the result. Release 1. with the specified axis removed.8. a reference to out is returned. the axes which are reduced are left in the result as dimensions with size one. It must have the same shape as the expected output. or if axis is None. axis : int. a measure of the spread of a distribution.array([[1. but the type is cast if necessary.3] [-.0]*4) >>> print x [[1 -.sum(axis=0) [8 5 12] >>> print type(x. out=None. optional If this is set to True.sum() 25 >>> print x.[7. With this option. optional Type to use in computing the variance. ddof : int. ddof=0) = <numpy. Parameters a : array_like Array containing numbers whose variance is desired.ma.sum(axis=0. The variance is computed for the flattened array by default.5 --] [7 -.9]] >>> print x. dtype=None.core.3]. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. out : ndarray. Returns the variance of the array elements.sum(axis=1) [4 5 16] >>> print x.int64’> numpy. a scalar is returned. mask=[0] + [1. the result will broadcast correctly against the original arr. By default ddof is zero.9]]. For arrays of integer type the default is float32. optional Alternate output array in which to place the result.5. If a is not an array. axis=None. The default is to compute the variance of the flattened array. Array objects . optional Axis along which the variance is computed. If self is a 0-d array.[4.ma.ma.NumPy Reference.ddof.6]._frommethod instance at 0x2820a28> Compute the variance along the specified axis.int64)[0]) <type ’numpy.

NumPy Reference, Release 1.8.1

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, mean, nanmean, nanstd, nanvar
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 a hypothetical 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, axis=0)
array([ 1., 1.])
>>> np.var(a, axis=1)
array([ 0.25, 0.25])

In single precision, var() can be inaccurate:
>>> a = np.zeros((2,512*512), dtype=np.float32)
>>> a[0,:] = 1.0
>>> a[1,:] = 0.1
>>> np.var(a)
0.20405951142311096

Computing the variance in float64 is more accurate:
>>> np.var(a, dtype=np.float64)
0.20249999932997387
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.20250000000000001

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

1.7. Masked arrays

383

NumPy Reference, Release 1.8.1

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.
mask = False,
fill_value = 1e+20)

1.],

MaskedArray.cumprod(axis=None, dtype=None, out=None)
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 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.

384

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

MaskedArray.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
>>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
>>> print marr.cumsum()
[0 1 3 -- -- -- 9 16 24 33]

MaskedArray.mean(axis=None, dtype=None, out=None)
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.
axis : int, optional
Axis along which the means are computed. The default is to compute the mean of the
flattened array.
dtype : dtype, optional

1.7. Masked arrays

385

NumPy Reference, Release 1.8.1

Type to use in computing the mean. For integer inputs, the default is float64; for floating
point, inputs it is the same as the input dtype.
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 will be cast if necessary.
Returns
mean : ndarray, see dtype parameter above
If out=None, returns a new array containing the mean values, otherwise a reference to
the output array is returned.
See Also:
numpy.ma.mean
Equivalent function.
numpy.mean
Equivalent function on non-masked arrays.
numpy.ma.average
Weighted average.
Examples
>>> a = np.ma.array([1,2,3], mask=[False, False, True])
>>> a
masked_array(data = [1 2 --],
mask = [False False True],
fill_value = 999999)
>>> a.mean()
1.5

MaskedArray.prod(axis=None, dtype=None, out=None)
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.
386

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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.])

MaskedArray.std(axis=None, dtype=None, out=None, ddof=0)
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.
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.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with
size one. With this option, the result will broadcast correctly against the original arr.
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.

1.7. Masked arrays

387

NumPy Reference, Release 1.8.1

See Also:
var, mean, nanmean, nanstd, nanvar
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 higheraccuracy accumulator using the dtype keyword can alleviate this issue.
Examples
>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949
>>> np.std(a, axis=0)
array([ 1., 1.])
>>> np.std(a, axis=1)
array([ 0.5, 0.5])

In single precision, std() can be inaccurate:
>>> a = np.zeros((2,512*512), dtype=np.float32)
>>> a[0,:] = 1.0
>>> a[1,:] = 0.1
>>> np.std(a)
0.45172946707416706

Computing the standard deviation in float64 is more accurate:
>>> np.std(a, dtype=np.float64)
0.44999999925552653

MaskedArray.sum(axis=None, dtype=None, out=None)
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

388

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.sum()
25
>>> print x.sum(axis=1)
[4 5 16]
>>> print x.sum(axis=0)
[8 5 12]
>>> print type(x.sum(axis=0, dtype=np.int64)[0])
<type ’numpy.int64’>

MaskedArray.var(axis=None, dtype=None, out=None, ddof=0)
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 : data-type, 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
Alternate 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 the calculation is N - ddof, where
N represents the number of elements. By default ddof is zero.
keepdims : bool, optional
1.7. Masked arrays

389

NumPy Reference, Release 1.8.1

If this is set to True, the axes which are reduced are left in the result as dimensions with
size one. With this option, the result will broadcast correctly against the original arr.
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, mean, nanmean, nanstd, nanvar
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 a hypothetical 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, axis=0)
array([ 1., 1.])
>>> np.var(a, axis=1)
array([ 0.25, 0.25])

In single precision, var() can be inaccurate:
>>> a = np.zeros((2,512*512), dtype=np.float32)
>>> a[0,:] = 1.0
>>> a[1,:] = 0.1
>>> np.var(a)
0.20405951142311096

Computing the variance in float64 is more accurate:
>>> np.var(a, dtype=np.float64)
0.20249999932997387
>>> ((1-0.55)**2 + (0.1-0.55)**2)/2
0.20250000000000001

Minimum/maximum
Continued on next page

390

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

Table 1.96 – continued from previous page
ma.argmax(a[, axis, fill_value])
ma.argmin(a[, axis, fill_value])
ma.max(obj[, axis, out, fill_value])
ma.min(obj[, axis, out, fill_value])
ma.ptp(obj[, axis, out, fill_value])
ma.MaskedArray.argmax([axis, fill_value, out])
ma.MaskedArray.argmin([axis, fill_value, out])
ma.MaskedArray.max([axis, out, fill_value])
ma.MaskedArray.min([axis, out, fill_value])
ma.MaskedArray.ptp([axis, out, fill_value])

Function version of the eponymous method.
Returns array of indices of the maximum values along the given axis.
Return the maximum along a given axis.
Return the minimum along a given axis.
Return (maximum - minimum) along the the given dimension (i.e.
Returns array of indices of the maximum values along the given axis.
Return array of indices to the minimum values along the given axis.
Return the maximum along a given axis.
Return the minimum along a given axis.
Return (maximum - minimum) along the the given dimension (i.e.

numpy.ma.argmax(a, axis=None, fill_value=None)
Function version of the eponymous method.
numpy.ma.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.
mum_fill_value(self._data) is used instead.

If None, the output of maxi-

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])

numpy.ma.max(obj, axis=None, out=None, fill_value=None)
Return the maximum along a given axis.
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.

1.7. Masked arrays

391

NumPy Reference, Release 1.8.1

fill_value : {var}, optional
Value used to fill in the masked values.
mum_fill_value().

If None, use the output of maxi-

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.min(obj, axis=None, out=None, fill_value=None)
Return the minimum along a given axis.
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.
minimum_fill_value.

If None, use the output of

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.
numpy.ma.ptp(obj, axis=None, out=None, fill_value=None)
Return (maximum - minimum) along the the given dimension (i.e. peak-to-peak value).
Parameters
axis : {None, int}, optional
Axis along which to find the peaks. If None (default) the flattened array is used.
out : {None, array_like}, 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.
fill_value : {var}, optional
Value used to fill in the masked values.
Returns
ptp : ndarray.

392

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

A new array holding the result, unless out was specified, in which case a reference to
out is returned.
MaskedArray.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.
mum_fill_value(self._data) is used instead.

If None, the output of maxi-

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])

MaskedArray.argmin(axis=None, fill_value=None, out=None)
Return array of indices to the minimum values along the given axis.
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.
mum_fill_value(self._data) is used instead.

If None, the output of mini-

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.

1.7. Masked arrays

393

NumPy Reference, Release 1.8.1

Examples
>>> x = np.ma.array(arange(4), mask=[1,1,0,0])
>>> x.shape = (2,2)
>>> print x
[[-- --]
[2 3]]
>>> print x.argmin(axis=0, fill_value=-1)
[0 0]
>>> print x.argmin(axis=0, fill_value=9)
[1 1]

MaskedArray.max(axis=None, out=None, fill_value=None)
Return the maximum along a given axis.
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.
mum_fill_value().

If None, use the output of maxi-

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.
MaskedArray.min(axis=None, out=None, fill_value=None)
Return the minimum along a given axis.
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.
minimum_fill_value.

If None, use the output of

Returns
amin : array_like
New array holding the result. If out was specified, out is returned.
See Also:

394

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

minimum_fill_value
Returns the minimum filling value for a given datatype.
MaskedArray.ptp(axis=None, out=None, fill_value=None)
Return (maximum - minimum) along the the given dimension (i.e. peak-to-peak value).
Parameters
axis : {None, int}, optional
Axis along which to find the peaks. If None (default) the flattened array is used.
out : {None, array_like}, 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.
fill_value : {var}, optional
Value used to fill in the masked values.
Returns
ptp : ndarray.
A new array holding the result, unless out was specified, in which case a reference to
out is returned.
Sorting
ma.argsort(a[, axis, kind, order, fill_value])
ma.sort(a[, axis, kind, order, endwith, ...])
ma.MaskedArray.argsort([axis, kind, order, ...])
ma.MaskedArray.sort([axis, kind, order, ...])

Return an ndarray of indices that sort the array along the specified axis.
Sort the array, in-place
Return an ndarray of indices that sort the array along the specified axis.
Sort the array, in-place

numpy.ma.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.
a[index_array] yields a sorted a.

1.7. Masked arrays

In other words,

395

NumPy Reference, Release 1.8.1

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
>>> a = np.ma.array([3,2,1], mask=[False, False, True])
>>> a
masked_array(data = [3 2 --],
mask = [False False True],
fill_value = 999999)
>>> a.argsort()
array([1, 0, 2])

numpy.ma.sort(a, axis=-1, kind=’quicksort’, order=None, endwith=True, fill_value=None)
Sort the array, in-place
Parameters
a : array_like
Array to be sorted.
axis : int, optional
Axis along which to sort. If None, the array is flattened before sorting. The default is
-1, which sorts along the last axis.
kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, optional
Sorting algorithm. Default is ‘quicksort’.
order : list, optional
When a is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields.
endwith : {True, False}, optional
Whether missing values (if any) should be forced in the upper indices (at the end of the
array) (True) or lower indices (at the beginning).
fill_value : {var}, optional
Value used internally for the masked values. If fill_value is not None, it supersedes
endwith.
Returns
sorted_array : ndarray
Array of the same type and shape as a.
See Also:

396

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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
>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # Default
>>> a.sort()
>>> print a
[1 3 5 -- --]
>>>
>>>
>>>
>>>
[--

a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
# Put missing values in the front
a.sort(endwith=False)
print a
-- 1 3 5]

>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # fill_value takes over endwith
>>> a.sort(endwith=False, fill_value=3)
>>> print a
[1 -- -- 3 5]

MaskedArray.argsort(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

1.7. Masked arrays

397

NumPy Reference, Release 1.8.1

Array of indices that sort a along the specified axis.
a[index_array] yields a sorted a.

In other words,

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
>>> a = np.ma.array([3,2,1], mask=[False, False, True])
>>> a
masked_array(data = [3 2 --],
mask = [False False True],
fill_value = 999999)
>>> a.argsort()
array([1, 0, 2])

MaskedArray.sort(axis=-1, kind=’quicksort’, order=None, endwith=True, fill_value=None)
Sort the array, in-place
Parameters
a : array_like
Array to be sorted.
axis : int, optional
Axis along which to sort. If None, the array is flattened before sorting. The default is
-1, which sorts along the last axis.
kind : {‘quicksort’, ‘mergesort’, ‘heapsort’}, optional
Sorting algorithm. Default is ‘quicksort’.
order : list, optional
When a is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields.
endwith : {True, False}, optional
Whether missing values (if any) should be forced in the upper indices (at the end of the
array) (True) or lower indices (at the beginning).
fill_value : {var}, optional
Value used internally for the masked values. If fill_value is not None, it supersedes
endwith.
Returns
sorted_array : ndarray
Array of the same type and shape as a.

398

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

See Also:
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
>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # Default
>>> a.sort()
>>> print a
[1 3 5 -- --]
>>>
>>>
>>>
>>>
[--

a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
# Put missing values in the front
a.sort(endwith=False)
print a
-- 1 3 5]

>>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0])
>>> # fill_value takes over endwith
>>> a.sort(endwith=False, fill_value=3)
>>> print a
[1 -- -- 3 5]

Algebra
ma.diag(v[, k])
ma.dot(a, b[, strict])
ma.identity(n[, dtype])
ma.inner(a, b)
ma.innerproduct(a, b)
ma.outer(a, b)
ma.outerproduct(a, b)
ma.trace(self[, offset, axis1, axis2, ...])
ma.transpose(a[, axes])
ma.MaskedArray.trace([offset, axis1, axis2, ...])
ma.MaskedArray.transpose(*axes)

Extract a diagonal or construct a diagonal array.
Return the dot product of two arrays.
Return the identity array.
Inner product of two arrays.
Inner product of two arrays.
Compute the outer product of two vectors.
Compute the outer product of two vectors.
Return the sum along diagonals of the array.
Permute the dimensions of an array.
Return the sum along diagonals of the array.
Returns a view of the array with axes transposed.

numpy.ma.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.
1.7. Masked arrays

399

NumPy Reference, Release 1.8.1

See Also:
numpy.diag
Equivalent function for ndarrays.
numpy.ma.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
>>> a = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[1, 0, 0], [0, 0, 0]])
>>> b = ma.array([[1, 2], [3, 4], [5, 6]], mask=[[1, 0], [0, 0], [0, 0]])
>>> np.ma.dot(a, b)
masked_array(data =
[[21 26]
[45 64]],
mask =
[[False False]
[False False]],
fill_value = 999999)
>>> np.ma.dot(a, b, strict=True)
masked_array(data =
[[-- --]
[-- 64]],
mask =
[[ True True]
[ True False]],
fill_value = 999999)

numpy.ma.identity(n, dtype=None) = <numpy.ma.core._convert2ma instance at 0x2820d40>
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.

400

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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.]])

numpy.ma.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.
einsum
Einstein summation convention.
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:

1.7. Masked arrays

401

NumPy Reference, Release 1.8.1

>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])

An example where b is a scalar:
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])

numpy.ma.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.
einsum
Einstein summation convention.
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)

402

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

array([[ 14, 38, 62],
[ 86, 110, 134]])

An example where b is a scalar:
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])

numpy.ma.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 [R48]
is:
[[a0*b0
[a1*b0
[ ...
[aM*b0

a0*b1 ... a0*bN ]
.
.
aM*bN ]]

Parameters
a : (M,) array_like
First input vector. Input is flattened if not already 1-dimensional.
b : (N,) array_like
Second input vector. Input is flattened if not already 1-dimensional.
Returns
out : (M, N) ndarray
out[i, j] = a[i] * b[j]
See Also:
inner, einsum
Notes
Masked values are replaced by 0.
References
[R48]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:
>>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
>>> rl
array([[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.]])
>>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
>>> im
array([[ 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
[ 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],

1.7. Masked arrays

403

NumPy Reference, Release 1.8.1

[ 0.-1.j, 0.-1.j,
[ 0.-2.j, 0.-2.j,
>>> grid = rl + im
>>> grid
array([[-2.+2.j, -1.+2.j,
[-2.+1.j, -1.+1.j,
[-2.+0.j, -1.+0.j,
[-2.-1.j, -1.-1.j,
[-2.-2.j, -1.-2.j,

0.-1.j,
0.-2.j,

0.-1.j,
0.-2.j,

0.-1.j],
0.-2.j]])

0.+2.j,
0.+1.j,
0.+0.j,
0.-1.j,
0.-2.j,

1.+2.j,
1.+1.j,
1.+0.j,
1.-1.j,
1.-2.j,

2.+2.j],
2.+1.j],
2.+0.j],
2.-1.j],
2.-2.j]])

An example using a “vector” of letters:
>>> x = np.array([’a’, ’b’, ’c’], dtype=object)
>>> np.outer(x, [1, 2, 3])
array([[a, aa, aaa],
[b, bb, bbb],
[c, cc, ccc]], dtype=object)

numpy.ma.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 [R49]
is:
[[a0*b0
[a1*b0
[ ...
[aM*b0

a0*b1 ... a0*bN ]
.
.
aM*bN ]]

Parameters
a : (M,) array_like
First input vector. Input is flattened if not already 1-dimensional.
b : (N,) array_like
Second input vector. Input is flattened if not already 1-dimensional.
Returns
out : (M, N) ndarray
out[i, j] = a[i] * b[j]
See Also:
inner, einsum
Notes
Masked values are replaced by 0.
References
[R49]
Examples
Make a (very coarse) grid for computing a Mandelbrot set:

404

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> rl = np.outer(np.ones((5,)), np.linspace(-2, 2, 5))
>>> rl
array([[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.],
[-2., -1., 0., 1., 2.]])
>>> im = np.outer(1j*np.linspace(2, -2, 5), np.ones((5,)))
>>> im
array([[ 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j, 0.+2.j],
[ 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j, 0.+1.j],
[ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],
[ 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j, 0.-1.j],
[ 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j, 0.-2.j]])
>>> grid = rl + im
>>> grid
array([[-2.+2.j, -1.+2.j, 0.+2.j, 1.+2.j, 2.+2.j],
[-2.+1.j, -1.+1.j, 0.+1.j, 1.+1.j, 2.+1.j],
[-2.+0.j, -1.+0.j, 0.+0.j, 1.+0.j, 2.+0.j],
[-2.-1.j, -1.-1.j, 0.-1.j, 1.-1.j, 2.-1.j],
[-2.-2.j, -1.-2.j, 0.-2.j, 1.-2.j, 2.-2.j]])

An example using a “vector” of letters:
>>> x = np.array([’a’, ’b’, ’c’], dtype=object)
>>> np.outer(x, [1, 2, 3])
array([[a, aa, aaa],
[b, bb, bbb],
[c, cc, ccc]], dtype=object)

numpy.ma.trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None) a.trace(offset=0, axis1=0,
axis2=1, dtype=None, out=None) = <numpy.ma.core._frommethod instance at
0x28209e0>
Return the sum along diagonals of the array.
Refer to numpy.trace for full documentation.
See Also:
numpy.trace
equivalent function
numpy.ma.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
>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>>> x

1.7. Masked arrays

405

NumPy Reference, Release 1.8.1

masked_array(data =
[[0 1]
[2 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)
>>> ma.transpose(x)
masked_array(data =
[[0 2]
[1 --]],
mask =
[[False False]
[False True]],
fill_value = 999999)

MaskedArray.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
Refer to numpy.trace for full documentation.
See Also:
numpy.trace
equivalent function
MaskedArray.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 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 a‘s 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

406

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

>>> a = np.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
[3, 4]])
>>> a.transpose()
array([[1, 3],
[2, 4]])
>>> a.transpose((1, 0))
array([[1, 3],
[2, 4]])
>>> a.transpose(1, 0)
array([[1, 3],
[2, 4]])

Polynomial fit
ma.vander(x[, n])
ma.polyfit(x, y, deg[, rcond, full, w, cov])

Generate a Van der Monde matrix.
Least squares polynomial fit.

numpy.ma.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 raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression
in each row is named for 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.
Examples
>>> x = np.array([1, 2, 3, 5])
>>> N = 3
>>> np.vander(x, N)
array([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> np.column_stack([x**(N-1-i) for i in range(N)])
array([[ 1, 1, 1],
[ 4, 2, 1],

1.7. Masked arrays

407

NumPy Reference, Release 1.8.1

[ 9,
[25,

3,
5,

1],
1]])

>>> x = np.array([1, 2, 3, 5])
>>> np.vander(x)
array([[ 1,
1,
1,
1],
[ 8,
4,
2,
1],
[ 27,
9,
3,
1],
[125, 25,
5,
1]])

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

numpy.ma.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
Least squares polynomial fit.
Fit a polynomial p(x) = p[0] * x**deg + ...
vector of coefficients p that minimises the squared error.

+ p[deg] of degree deg to points (x, y). Returns a

Parameters
x : array_like, shape (M,)
x-coordinates of the M sample points (x[i], y[i]).
y : array_like, shape (M,) or (M, K)
y-coordinates of the sample points. Several data sets of sample points sharing the same
x-coordinates can be fitted at once by passing in a 2D-array that contains one dataset
per column.
deg : int
Degree of the fitting polynomial
rcond : float, optional
Relative condition number of the fit. Singular values smaller than this relative to the
largest singular value will be ignored. The default value is len(x)*eps, where eps is the
relative precision of the float type, about 2e-16 in most cases.
full : bool, optional
Switch determining nature of return value. When it is False (the default) just the coefficients are returned, when True diagnostic information from the singular value decomposition is also returned.
w : array_like, shape (M,), optional
weights to apply to the y-coordinates of the sample points.
cov : bool, optional
Return the estimate and the covariance matrix of the estimate If full is True, then cov is
not returned.
Returns
p : ndarray, shape (M,) or (M, K)

408

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

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 coefficient matrix, its singular values, and the specified value of rcond. For more details, see
linalg.lstsq.
V : ndaray, shape (M,M) or (M,M,K)
The covariance matrix of the polynomial coefficient estimates. The diagonal of this matrix are the variance estimates for each coefficient. If y is a 2-d array, then the covariance
matrix for the k-th data set are in V[:,:,k]
Warns
RankWarning
The rank of the coefficient matrix in the least-squares fit is deficient. The warning is
only raised if full = False.
The warnings can be turned off by
>>> import warnings
>>> warnings.simplefilter(’ignore’, np.RankWarning)

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
[R50], [R51]
Examples
>>> x =
>>> y =
>>> z =
>>> z
array([

np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0])
np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])
np.polyfit(x, y, 3)
0.08703704, -0.81349206,

1.69312169, -0.03968254])

It is convenient to use poly1d objects for dealing with polynomials:
>>> p = np.poly1d(z)
>>> p(0.5)
0.6143849206349179
>>> p(3.5)
-0.34732142857143039
>>> p(10)
22.579365079365115

1.7. Masked arrays

409

NumPy Reference, Release 1.8.1

High-order polynomials may oscillate wildly:
>>> p30 = np.poly1d(np.polyfit(x, y, 30))
/... RankWarning: Polyfit may be poorly conditioned...
>>> p30(4)
-0.80000000000000204
>>> p30(5)
-0.99999999999999445
>>> p30(4.5)
-0.10547061179440398

Illustration:

>>> import matplotlib.pyplot as plt
>>> xp = np.linspace(-2, 6, 100)
>>> plt.plot(x, y, ’.’, xp, p(xp), ’-’, xp, p30(xp), ’--’)
[<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>, <matplotl
>>> 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

Clipping and rounding
ma.around
ma.clip(a, a_min, a_max[, out])
ma.round(a[, decimals, out])
ma.MaskedArray.clip(a_min, a_max[, out])
ma.MaskedArray.round([decimals, out])

Round an array to the given number of decimals.
Clip (limit) the values in an array.
Return a copy of a, rounded to ‘decimals’ places.
Return an array whose values are limited to [a_min, a_max].
Return a with each element rounded to the given number of decimals.

numpy.ma.around = <numpy.ma.core._MaskedUnaryOperation instance at 0x2816440>
Round an array to the given number of decimals.
Refer to around for full documentation.
See Also:
around

410

Chapter 1. Array objects

NumPy Reference, Release 1.8.1

equivalent function
numpy.ma.clip(a, a_min, a_max, out=None)
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of
[0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
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])

numpy.ma.round(a, decimals=0, out=None)
Return a copy of a, rounded to ‘decimals’ places.
When ‘decimals’ is negative, it specifies the number of positions to the left of the decimal point. The real and
imaginary parts of complex numbers are rounded separately. Nothing is done if the array is not of float type and
‘decimals’ is greater than or equal to 0.
Parameters
decimals : int

1.7. Masked arrays

411

ediff1d(arr[.] stop[.. . Refer to numpy. If not given.around equivalent function Miscellanea ma. a_max]. to_end.allequal(a.][.allclose(a. to_begin]) ma. Release 1. numpy.1 Number of decimals to round to. See Also: 412 Chapter 1. b[. returns a default copy of a. Returns y : bool Returns True if the two arrays are equal within the given tolerance. optional Whether masked values in a or b are considered equal (True) or not (False).choose(indices. out=None) Return a with each element rounded to the given number of decimals. Apply a function to 1-D slices along the given axis. Return a masked array with elements from x or y.apply_along_axis(func1d. fill_value : bool. False otherwise. If either array contains NaN.arange([start. step. out=None) Return an array whose values are limited to [a_min. dtype]) ma. b : array_like Input arrays to compare. atol]) ma.around for full documentation. Compute the differences between consecutive elements of an array. axis. a_max. b[. y]) Return True if all entries of a and b are equal. x. See Also: numpy. Array objects .NumPy Reference. then False is returned. Return an array representing the indices of a grid. Return evenly spaced values within a given interval. Parameters a.) ma.ma. out : array_like Existing array to use for output..where(condition[. Refer to numpy. mode]) ma. arr. fill_value=True) Return True if all entries of a and b are equal. using Returns True if two arrays are element-wise equal within a tolerance. May be negative. masked_equal.clip for full documentation. the mask of a is lost! MaskedArray. out.8. dtype]) ma.round(decimals=0. using fill_value as a truth value where either or both are masked. See Also: numpy. fill_value]) ma.clip(a_min. depending on condition.allequal(a. choices[.clip equivalent function MaskedArray. b. rtol. Notes If out is given and does not have a mask attribute. Use an index array to construct a new array from a set of choices.indices(dimensions[.

1 all. then allclose returns True: absolute(‘a‘ . fill_value=False) False >>> ma. Default is 1e-8. They are considered equal by default. optional Relative tolerance. False otherwise. >>> ma. 1]) >>> a masked_array(data = [10000000000. 1e-7.ma. Returns y : bool Returns True if the two arrays are equal within the given tolerance. The absolute difference is equal to atol. Notes If the following equation is element-wise True. fill_value=1e+20) >>> b = array([1e10.‘b‘) <= (‘atol‘ + ‘rtol‘ * absolute(‘b‘)) Return True if all elements of a and b are equal subject to given tolerances. mask = [False False True].allequal(a.allclose Examples >>> a = ma. numpy. Release 1. b) True -4. then False is returned. Parameters a.0 1e-07 --]. Default is 1e-5.00000000e+10. atol=1e-08) Returns True if two arrays are element-wise equal within a tolerance. any. optional Absolute tolerance.20000000e+01]) numpy. atol : float.7. any numpy. The relative difference is equal to rtol * b. Masked arrays 413 . optional Whether masked values in a and b are considered equal (True) or not (False). 42. rtol : float.allequal(a. 1e-7. b.ma. masked_equal=True. depending on the masked_equal argument.0]) >>> b array([ 1. This function is equivalent to allclose except that masked values are treated as equal (default) or unequal. 1.NumPy Reference. If either array contains NaN.8. 1. -42.allclose(a. b.00000000e-07. b : array_like Input arrays to compare. mask=[0.allclose the non-masked allclose. 0. See Also: all. masked_equal : bool.array([1e10.0]. rtol=1e-05.

42.0]. b) True >>> ma.0]. b) True >>> ma. 0. except along the axis dimension.00001e10. Release 1.0].0]. mask = [False False True]. mask=[0. b) False >>> a = ma. axis : integer Axis along which arr is sliced. mask=[0. 42. 0. mask=[0. masked_equal=False) False Masked values are not compared directly. *args. args : any Additional arguments to func1d.ma. mask=[0.0]. -42. 1e-9. b. *args) where func1d operates on 1-D arrays and a is a 1-D slice of arr along axis.allclose(a. where the length of outarr is equal to the size of the return value of func1d. 1e-8. 414 Chapter 1. 1]) >>> b = ma. mask=[0.array([1. 0. 0.0]. 1]) >>> b = ma.allclose(a. It is applied to 1-D slices of arr along the specified axis. 1]) >>> ma.00001e10. Returns apply_along_axis : ndarray The output array. b.allclose(a.apply_along_axis(func1d. 0. Array objects . 0. Execute func1d(a. axis.NumPy Reference. The shape of outarr is identical to the shape of arr. masked_equal=False) False numpy. 1e-9. 1e-8. 1e-8.array([1e10. 1]) >>> ma. fill_value = 1e+20) >>> b = ma. 1]) >>> ma.0 1e-07 --]. 1e-7. arr. Parameters func1d : function This function should accept 1-D arrays.1 Examples >>> a = ma. >>> a = ma.array([1. 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.array([1e10. -42.array([1e10. 1]) >>> a masked_array(data = [10000000000. mask=[0. **kwargs) Apply a function to 1-D slices along the given axis. 42.allclose(a.allclose(a.array([1e10. arr : ndarray Input array.8. 42.

apply_along_axis(my_func. stop : number End of interval. If dtype is not given.. 4.ma. except in some cases where step is not an integer and floating point round-off affects the length of out.array([[1. this rule may result in the last element of out being greater than stop. 1..]) >>> np. For any output out. For integer arguments the function is equivalent to the Python built-in range function. For floating point arguments.1.7].8. 6. It is better to use linspace for these cases. optional Start of interval.. Masked arrays 415 . Returns arange : ndarray Array of evenly spaced values. Release 1. the length of the result is ceil((stop start)/step).out[i].3]. [3. but returns an ndarray rather than a list. 7.apply_along_axis(my_func. this is the distance between two adjacent values. 8]. b) array([[1. step : number. [5.3. dtype : dtype The type of the output array.ma. optional Spacing between values.. step ]. the number of dimensions in outarr is the same as arr. return (a[0] + a[-1]) * 0. infer the data type from the other input arguments. such as 0. The default step size is 1.6]. stop) (in other words. [7. stop[. start must also be given. 0.9]]) >>> np. 5. [2. 8. the interval including start but excluding stop)..core. b) array([ 2. 6]]) numpy.9]. [4. 1. 5.5 >>> b = np.6]]) >>> np.array([[8. [4.7. 5.1 Examples >>> def my_func(a): . See Also: linspace Evenly spaced numbers with careful handling of endpoints.apply_along_axis(sorted.5. the results will often not be consistent.8.]) For a function that doesn’t return a scalar.1. >>> b = np. The interval includes this value. If step is specified. The default start value is 0. When using a non-integer step..2. out[i+1] .2...arange([start ]._convert2ma instance at 0x2820bd8> Return evenly spaced values within a given interval. Values are generated within the half-open interval [start. Parameters start : number. 9]. dtype=None) = <numpy. """Average first and last element of a 1-D array""" . 1. The interval does not include this value.NumPy Reference. Because of floating point overflow. b) array([ 4.

the result will be inserted into this array.arange(3.arange(3. 0]) >>> np. where n is the number of choices. The index array and all of the choices should be broadcastable to the same shape.. 5. choices. mode=’raise’) Use an index array to construct a new array from a set of choices. 1. Examples >>> np.8. choice) masked_array(data = [3 2 1]. Parameters a : ndarray of ints This array must contain integers in [0.0) array([ 0. Given an array of integers and a set of n choice arrays.ma.arange(3) array([0. n-1].ma. the new array will have the value that choices[i] contains in the same place.1.choose(a. 4. out : array. choices : sequence of arrays Choice arrays. Release 1.]) >>> np. mode : {‘raise’.1]. this method will create a new array that merges each of the choice arrays.choose(indices.2.arange(3. ‘wrap’. mgrid Grid-shaped arrays of evenly spaced numbers in N-dimensions.3. Array objects .. • ‘raise’ : raise an error • ‘wrap’ : wrap around • ‘clip’ : clip to the range Returns merged_array : array See Also: choose equivalent function Examples >>> choice = np.2) array([3.array([[1.1 ogrid Arrays of evenly spaced numbers in N-dimensions.array([2.7. 5]) numpy. 6]) >>> np.3]]) >>> a = np. 2. ‘clip’}. optional If provided. 416 Chapter 1. It should be of the appropriate shape and dtype. Where a value in a is i.2]. optional Specifies how out-of-bounds indices will behave. 2]) >>> np. 1. [2. [3.7) array([3. out=None.NumPy Reference. 1.

8...ma. 1]]) >>> grid[1] # column indices array([[0. Explicitly: grid[k. 3)) >>> grid. 1. fill_value=999999) numpy.i0. . 2.) + See Also: mgrid. Compute an array where the subarrays contain index values 0. grid. tuple(dimensions).i1...iN-1] = ik Examples >>> grid = np. The subarrays grid[k] contains the N-D array of indices along the k-th axis. meshgrid Notes The output shape is obtained by prepending the number of dimensions in front of the tuple of dimensions. dtype : dtype. Parameters dimensions : sequence of ints The shape of the grid..ediff1d for details. 1. to_end=None.indices((2. 1.1 mask = False. varying only along the corresponding axis... 0..1.ediff1d that takes masked values into account. 3) >>> grid[0] # row indices array([[0.r0. if dimensions is a tuple (r0.NumPy Reference. to_begin=None) Compute the differences between consecutive elements of an array.rN-1).7.. 1.. See Also: numpy.ediff1d(arr. i. dtype=<type ‘int’>) Return an array representing the indices of a grid..ma. This function is the equivalent of numpy.indices(dimensions. [0. Returns grid : ndarray The array of grid indices. 2]]) The indices can be used as an index into an array. rN-1) of length N. 0]. Masked arrays 417 . see numpy. optional Data type of the result. the output shape is (N..shape = (len(dimensions).shape (2. 2].. [1..ediff1d Equivalent function for ndarrays.e. Release 1. numpy.

. 3)) >>> x[row. otherwise from y. mask=[[0. [4. 6]]) Note that it would be more straightforward in the above example to extract the required elements directly with x[:2. y=None) Return a masked array with elements from x or y. 0..). 3). Returns out : MaskedArray or tuple of ndarrays The resulting masked array if x and y were given. 5. y : array_like.8.1 >>> x = np.where(x > 5. .0]] 1.0 --] [6. and from y otherwise. Array objects . If neither x nor y are given.. [1.-3.where Equivalent function in the top-level NumPy module.ma. otherwise the result of condition. x.nonzero().where(x > 5) # return the indices where x > 5 (array([2. bool The condition to meet. 0]. numpy.8.reshape(3.8.arange(20).1416] [-. array([0. 2]). Release 1. 1. or be broadcast-able to that shape. 0]]) >>> print x [[0.nonzero()).ma. For each True element. x.0]] >>> np.8 The Array Interface 418 Chapter 1. 4) >>> row.1416) [[-3..NumPy Reference.where(condition. col = np. x=None.reshape(5. Returns a masked array.1416 --] [6.1416 -. 1. See Also: numpy.2. Examples >>> x = np.0 -.4. -3. shaped like condition. optional Values from which to choose. 1. 2])) >>> print np. 1].ma.indices((2. where the elements are from x when condition is True. depending on condition. col] array([[0.0 -.arange(9. yield the corresponding element from x. :3]. Parameters condition : array_like. 2].0] [-. [0. x and y need to have the same shape as condition.-3. .0 -.array(np. the function returns a tuple of indices where condition is True (the result of condition.ma.

a character code giving the basic type of the array. The basic type character codes are: t b i u f c O S U V Bit field (following integer gives the number of bits in the bit field). Boolean (integer type where all values are only True or False) Integer Unsigned integer Floating point Complex floating point Object (i. Objects wishing to be considered an N-dimensional array in application code should support at least one of these attributes. >: big-endian. The homogeneous N-dimensional array interface is a default mechanism for objects to share N-dimensional array memory and information. Cython provides a way to write code that supports the buffer protocol with Python versions older than 2. Both are separate attributes. The optional keys in the dictionary have implied defaults if they are not provided. Note that these integers could be larger than the platform “int” or “long” could hold (a Python int is a C long).NumPy Reference. Each entry is an integer (a Python int or long). The keys are: shape (required) Tuple whose elements are the array size in each dimension. or by using Py_LONG_LONG as the C type for the shapes. Release 1. This interface describes homogeneous arrays in the sense that each item of the array has the same “type”.8.e. and an integer providing the number of bytes the type uses.6 and 3. The Array Interface 419 . The interface consists of a Python-side and a C-side using two attributes.0 for any extension module to use. the memory contains a pointer to PyObject) String (fixed-length sequence of char) Unicode (fixed-length sequence of Py_UNICODE) Other (void * – each item is a fixed-size chunk of memory) 1. 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. see the Cython numpy tutorial.1 Python side This approach to the interface consists of the object having an __array_interface__ attribute. standardized API to Python 2. |: not-relevant).8. 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 type can be very simple or it can be a quite arbitrary and complicated C-like structure. 1. Cython‘s buffer array support uses the PEP 3118 API. It is up to the code using this attribute to handle this appropriately.1 Note: This page describes the numpy-specific API for accessing the contents of a numpy array from other C extensions. __array_interface__ A dictionary of items (3 required and 5 optional). 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 other’s data buffers intelligently whenever possible.6 because it has a backward-compatible implementation utilizing the array interface described here.8. There are two ways to use the interface: A Python side and a C-side. either by raising an error when overflow is possible. PEP 3118 – The Revised Buffer Protocol introduces similar.

Notice. Default: None (All array values are valid) offset (optional) An integer offset into the array data region. In this case. or by using Py_LONG_LONG in C.8. the values may be larger than can be represented by a C “int” or “long”. As with shape. If this key is not present (or returns None). Normally. Very complicated structures can be described using this generic interface. For example. In this model. 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. that each element of the array is still of the same data-type. No repeats are assumed if this is not given. The elements of each tuple in the list are 1. This could also be a tuple of (’full name’. This attribute can also be an object exposing the buffer interface which will be used to share the data. This pointer must point to the first element of data (in other words any offset is always ignored in this case). this attribute would be used when typestr is V[0-9]+. 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. however. All elements of the mask array should be interpreted only as true or not true indicating which elements of this array are valid. Default: [(”. The idea is to support descriptions of C-like structs (records) that make up array elements.20. the default strides tuple for an object whose array entries are 8 bytes long and whose shape is (10.An optional shape tuple providing how many times this part of the record should be repeated. The second entry in the tuple is a read-only flag (true means the data area is read-only). either by raising an error. 420 Chapter 1.NumPy Reference. A reference to the object exposing the array interface must be stored by the new object if the memory area is to be secured. 240. 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. but this is not a requirement.Either a basic-type description string as in typestr or another list (for nested records) 3. 2. Release 1.1 descr (optional) A list of tuples providing a more detailed description of the memory layout for each item in the homogeneous array. The shape of this object should be “broadcastable” to the shape of the original array. 8) Default: None (C-style contiguous) mask (optional) None or an object exposing the array interface. Each tuple in the list has two or three elements.A string providing a name associated with this portion of the record. Array objects . This can only be used when data is None or returns a buffer object. ’basic_name’) where basic name would be a valid Python variable name representing the full name of the field. the calling code should handle this appropiately. Each entry must be an integer (a Python int or long). the offset key can be used to indicate the start of the buffer. The default is None which implies a C-style contiguous memory buffer.30) would be (4800. Some examples of using this interface are given below. the last dimension of the array varies the fastest. then memory sharing will be done through the buffer interface of the object itself.

int itemsize. /* void *data. /* Py_intptr_t *strides. Be sure to own a reference to the object when the PyCObject is created using PyCObject_FromVoidPtrAndDesc. NOTSWAPPED (0x200).NumPy Reference. /* /* /* /* /* /* Py_intptr_t *shape. Thanks to Scott Gilbert for these examples: In every case. 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. 1.simple sanity check */ number of dimensions */ kind in array --. but of course provides more information which may be important for various applications: 1. Be careful not to use this to invalidate objects exposing future versions of the interface. 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.1 Default: 0. 3 for this version). /* PyObject *descr. 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. Release 1. A final flag ARR_HAS_DESCR (0x800) indicates whether or not this structure has the arrdescr field.8. and WRITEABLE (0x400). either the data needs to be copied out.2 C-struct access This approach to the array interface allows for faster access to an array using only one attribute lookup and a welldefined C-structure. or a reference to the object exposing this attribute must be held to ensure the data is not freed.8. The data-bits are CONTIGUOUS (0x1). Also.8. New since June 16. FORTRAN (0x2). ALIGNED (0x100).3 Type description examples For clarity it is useful to provide some examples of the type description and corresponding __array_interface__ ‘descr’ entries. The field should not be accessed unless this flag is present.must set ARR_HAS_DESCR flag or this will be ignored. */ } PyArrayInterface.h as: typedef struct { int two. The Array Interface 421 . __array_struct__ A PyCObject whose voidptr member contains a pointer to a filled PyArrayInterface structure. version (required) An integer showing the version of the interface (i.character code of typestr */ size of each element */ flags indicating how the data should be interpreted */ must set ARR_HAS_DESCR bit to validate descr */ A length-nd array of shape information */ A length-nd array of stride information */ A pointer to the first element of the array */ NULL or data-description (same as descr key of __array_interface__) -. The PyArrayInterface structure is defined in numpy/ndarrayobject.e. /* contains the integer 2 -. int nd. This is now an explicit part of the interface. Objects exposing the __array_struct__ interface must also not reallocate their memory if other objects are referencing them. 1. the ‘descr’ key is optional. int flags.8. char typekind.

8.’>f4’)] * Complex double typestr == ’>c8’ descr == [(’real’. double data[16*4]. Array objects .(’’.4 Differences with Array interface (Version 2) The version 2 interface was very similar. (’little’. (’bval’. 422 Chapter 1. } typestr == ’|V516’ descr == [(’ival’. The desc member of the PyCObject returned from __array_struct__ was not specified. Release 1.(16. Usually. (’imag’.’<u2’). In particular: 1. The differences were largely asthetic.4))] * Padded structure struct { int ival.’|u1’). [(’sval’. (’b’.’>f8’.’|V4’).’>i4’).’|u1’).’>f4’)] * RGB Pixel data typestr == ’|V3’ descr == [(’r’.’|u1’). typestr == ’|V8’ (or ’>u8’) descr == [(’big’. } typestr == ’|V16’ descr == [(’ival’.’>f8’)] It should be clear that any record type could be described using this interface.’|u1’) ]) ] * Nested array struct { int ival.’|u1’)] * Mixed endian (weird but could happen). 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.’<i4’). (’cval’.’>f4’).’<i4’)] * Nested structure struct { int ival. (’sub’.(’dval’. The PyArrayInterface structure had no descr member at the end (and therefore no flag ARR_HAS_DESCR) 2.’>i4’). double dval. unsigned char cval. (’g’.’>i4’). unsigned char bval. it was the object exposing the array (so that a reference to it could be kept and destroyed when the C-object was destroyed). } typestr == ’|V8’ (or ’<u8’ if you want) descr == [(’ival’.NumPy Reference. 1.1 * Float data typestr == ’>f4’ descr == [(’’. (’data’. struct { unsigned short sval. } sub.8.

datetime64(’2005-02-25’) numpy.9. while the time units are hours (‘h’). The date units are years (‘Y’).datetime64(’2005-02-01’) Using UTC “Zulu” time: >>> np. The unit for internal storage is automatically selected from the form of the string. Starting in NumPy 1. 1. so named because “datetime” is already taken by the datetime library included in Python.NumPy Reference.7. but forcing a ‘days’ unit: >>> np. milliseconds (‘ms’).7.0. and can be either a date unit or a time unit.8.datetime64(’2005-02’) numpy.1 3. seconds (‘s’). The data type is called “datetime64”. and may undergo changes in future versions of NumPy. weeks (‘W’).7. 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__ 1. and some additional SI-prefix seconds-based units. minutes (‘m’). Datetimes and Timedeltas 423 . Note: The datetime API is experimental in 1. Example A simple ISO date: >>> np. The tuple returned from __array_interface__[’data’] used to be a hex-string (now it is an integer or a long integer).datetime64(’2005-02’.datetime64(’2005-02’) Specifying just the month.9.datetime64(’2005-02-25T03:30Z’) numpy. ’D’) numpy.datetime64(’2005-02-24T21:30-0600’) 1.9 Datetimes and Timedeltas New in version 1.1 Basic Datetimes The most basic way to create datetimes is from strings in ISO 8601 date or datetime format. there are core array data types which natively support datetime functionality. 4.0. Release 1.datetime64(’2005-02-25’) Using months for the unit: >>> np. and days (‘D’). months (‘M’).

in <module> TypeError: Cannot parse "2003-12-25" as unit ’s’ using casting rule ’same_kind’ 424 Chapter 1. Example All the dates for one month: >>> np. ’2002-02-03T13:56:03. Array objects . for example arange can be used to generate ranges of dates. ’2005-02-16’.172’]. dtype=’datetime64[D]’) >>> np. line 1. ’2005-02-24’.arange(’2005-02’. ’2005-02-17’. ’2005-02-08’. ’2005-02-28’]. they may still be representing the same moment of time. Release 1.datetime64(’2010-03-14T15Z’) == np.datetime64(’2003-12-25’. ’2005-02-13’. ’2005-02-06’.172-0600’]. ’2005-02-07’. ’2005-02-02’. ’2005-02-05’.datetime64(’2010-03-14T15:00:00. ’2010-08-13’]. and converting from a bigger unit like months to a smaller unit like days is considered a ‘safe’ cast because the moment of time is still being represented exactly. ’2005-02-25’.00Z’) True An important exception to this rule is between datetimes with date units and datetimes with time units. Example >>> np. ’2006-01-13’. ’2005-02-09’. ’2005-02-26’.datetime64(’2005-01-01’) True >>> np. ’2005-02-19’. ’2005-02-20’. dtype=’datetime64[ms]’) The datetime type works with many common NumPy functions. dtype=’datetime64’) array([’2001-01-01T12:00:00. Example >>> np. ’2005-02-23’. ’2006-01-13’. ’2010-08-13’].000-0600’. ’2005-02-22’. ’2005-02-03’.datetime64(’2005-02-25T03:30’) numpy. ’2005-02-27’. dtype=’datetime64[D]’) array([’2005-02-01’.datetime64(’2005-02-25T03:30-0600’) When creating an array of datetimes from a string. If two datetimes have different units. ’2005-02-04’. ’s’) Traceback (most recent call last): File "<stdin>".1 ISO 8601 specifies to use the local time zone if none is explicitly given: >>> np. ’2005-02-15’. ’2005-02-21’. dtype=’datetime64[D]’) The datetime object represents a single moment in time. it is still possible to automatically select the unit from the inputs.array([’2001-01-01T12:00’. This is because this kind of conversion generally requires a choice of timezone and particular time of day on the given date. by using the datetime type with generic units. ’2002-02-03T13:56:03. ’2005-02-14’. ’2005-03’. ’2005-02-12’. dtype=’datetime64’) array([’2007-07-13’. Example >>> np. ’2005-02-11’. ’2005-02-10’.NumPy Reference.array([’2007-07-13’.datetime64(’2005’) == np. ’2005-02-18’.8.

NumPy Reference. This means the supported dates are always a symmetric interval around the epoch.datetime64(’2011-06-15T12:00-0500’) >>> np.timedelta64(366. ’Y’) >>> np. months) which are treated specially.timedelta64(a.timedelta64(1.timedelta64(12.datetime64(’2009-01-01’) . Datetimes and Timedeltas work together to provide ways for simple datetime calculations. because how much time they represent changes depending on when they are used. While a timedelta day unit is equivalent to 24 hours.datetime64(’2009’) + np. in <module> TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y] to [D] according to the rule ’same_ 1. line 1.timedelta64(20.’D’) >>> np.datetime64(’2003-12-25’) == np. ’h’) numpy.datetime64(’2009-01-21’) >>> np. Example >>> a = np. ’D’) numpy. Because NumPy doesn’t have a physical quantities system in its core.datetime64(’2011-06-15T00:00’) + np. The length of the span is the range of a 64-bit integer times the length of the date or unit.9.timedelta64(1.2 Datetime and Timedelta Arithmetic NumPy allows the subtraction of two Datetime values.1 >>> np.’D’) 7.timedelta64(a.datetime64(’2008-01-01’) numpy. an operation which produces a number with a time unit.8. Datetimes are always stored based on POSIX time (though having a TAI mode which allows for accounting of leapseconds is proposed).0 There are two Timedelta units (‘Y’. there is no way to convert a month unit into days. the time span for ‘W’ (week) is exactly 7 times longer than the time span for ‘D’ (day). the timedelta64 data type was created to complement datetime64. and the time span for ‘D’ (day) is exactly 24 times longer than the time span for ‘h’ (hour). because different months have different numbers of days.’M’) >>> np. 1. Release 1. ’M’) numpy.9.timedelta64(12. called “time span” in the table below.np.datetime64(’2003-12-25T00Z’) False 1. Datetimes and Timedeltas 425 .’W’) / np.9.3 Datetime Units The Datetime and Timedelta data types support a large number of time units. For example. with a epoch of 1970-01-01T00:00Z. Example >>> np. ’D’) Traceback (most recent call last): File "<stdin>".timedelta64(1. years and ‘M’. as well as generic units which can be coerced into any of the other units based on input data.

7.0e15 AD] [1. 2262 AD] [ 1969 AD.2.5e16 BC.8.2. 2.busday_offset(’2011-06-25’.4 Business Day Functionality To allow the datetime to be used in contexts where only certain days of the week are valid.9e12 years +/.2e18 AD] [7.7e17 AD] [2. 1970 AD] [ 1969 AD.5e16 AD] Time span (relative) +/.7e13 BC. 2.2e18 BC.106 days +/.busday_offset(’2011-06-23’. The implementation is based on a “weekmask” containing 7 Boolean flags to indicate valid days.2 seconds Time span (absolute) [1. 1) numpy.9e9 BC.9. 2.1. busday_offset first applies a rule to roll the date to a valid business day.1.7e17 years +/. The rules most typically used are ‘forward’ and ‘backward’.datetime64(’2011-06-27’) >>> np.1. specific dates that are not valid days.datetime64(’2011-06-24’) >>> np. 294241 AD] [ 1678 AD. Example >>> np. 2) numpy.7e17 BC. then applies the offset. Release 1.busday_offset(’2011-06-25’.7e13 years +/.0e15 years +/.datetime64(’2011-06-27’) When an input date falls on the weekend or a holiday.2e18 years +/. 1970 AD] 1.9e6 BC.292 years +/. roll=’forward’) numpy.6e17 BC. line 1. 0.5e16 years Meaning hour minute second millisecond microsecond nanosecond picosecond femtosecond attosecond Time span (absolute) [9. roll=’forward’) numpy.2. The default for busday functions is that the only valid days are Monday through Friday (the usual business days).1 Here are the date units: Code Y M W D And here are the time units: Meaning year month week day Code h m s ms us ns ps fs as Time span (relative) +/.NumPy Reference.2.6e17 years +/. 1. custom weekmasks are possible that specify other sets of valid days. 2.6e17 AD] [1. Example >>> np. in <module> ValueError: Non-business day date in busday_offset >>> np.2. which simply raises an exception. 2) Traceback (most recent call last): File "<stdin>".9e6 years +/. The default rule is ‘raise’. 1.7e13 AD] [ 2.9e9 years +/. Array objects .9e9 AD] [ 2.datetime64(’2011-06-29’) 426 Chapter 1.busday_offset(’2011-06-25’. NumPy includes a set of “busday” (business day) functions. 9. 1.7.9.9e6 AD] [290301 BC. The function busday_offset allows you to apply offsets specified in business days to datetimes with a unit of ‘D’ (day).busday_offset(’2011-06-23’. The “busday” functions can additionally check a list of “holiday” dates.0e15 BC.9.6 hours +/. 1970 AD] [ 1969 AD.

datetime64(’2011-03-22’.busday_offset(’2011-03-22’.datetime64(’2011-03-23’.busday_offset(’2011-03-20’.datetime64(’2011-07-11’).datetime64(’2011-06-24’) >>> np. 1.datetime64(’2011-07-15’)) # a Friday True >>> np. In Canada and the U.is_busday(np. False.busday_offset(’2011-06-25’. Release 1. roll=’backward’) numpy.datetime64(’2011-07-16’)) # a Saturday False >>> np. Mother’s day is on the second Sunday in May.busday_offset(’2012-05’.is_busday(a) array([ True. weekmask=’Sun’) numpy. Example >>> np. 0. which can be computed with a custom weekmask. True. True.datetime64(’2011-07-18’)) >>> np.busday_offset(’2011-06-25’. use is_busday.1 >>> np. False]. True. roll=’backward’) numpy. Datetimes and Timedeltas 427 .’D’) When performance is important for manipulating many business dates with one particular choice of weekmask and holidays. True.is_busday(): To test a datetime64 value to see if it is a valid day.S. Example >>> np.’D’) >>> np.datetime64(’2011-07-16’).datetime64(’2011-03-21’..arange(np.datetime64(’2011-03-21’.’D’) >>> np.9. 0. roll=’forward’) numpy. Example The first business day on or after a date: >>> np.is_busday(np. 1. roll=’backward’) numpy.’D’) The function is also useful for computing some kinds of days like holidays.datetime64(’2011-06-28’) In some cases.busday_offset(’2011-03-20’. 0. roll=’forward’. an appropriate use of the roll and the offset is necessary to get a desired answer.8.NumPy Reference. np. dtype=’bool’) 1. 1. weekmask="Sat Sun") True >>> a = np. roll=’forward’) numpy.busday_offset(’2011-03-22’. 2. np.’D’) The first business day strictly after a date: >>> np.is_busday(np. roll=’backward’) numpy. there is an object busdaycalendar which stores the data necessary in an optimized form.datetime64(’2012-05-13’.

you can do this: Example >>> a = np. 1.7 Datetimes The NumPy 1.7 detects a unit based on the format of the string. weekmask = "MonTue Wed Thu\tFri" 1.arange(np.datetime64(’2011-07-18’). np. This section documents many of the changes that have taken place.: # NumPy 1. 0 == invalid day.count_nonzero(np. positions are Monday through Sunday. np. The parser in NumPy 1.6 always creates microsecond (us) units by default. Here is a comparison. These examples specify the “busday” default of Monday through Friday being valid days.7. 1 == valid day weekmask = "1111100" # string ’0’ == invalid day.datetime64(’1979-03-22’) 1979-03-22 00:00:00 428 Chapter 1.5 Differences Between 1.6. 1.1 np.6 release includes a more primitive datetime data type than 1. Some examples: # Positional sequences. use busday_count: Example >>> np. 1. 1.busday_count(): To find how many valid days there are in a specified range of datetime64 dates.9. Array objects . String Parsing The datetime string parser in NumPy 1. whereas 1.datetime64(’2011-07-18’)) 5 >>> np.7 is quite strict about only accepting ISO 8601 dates. ’1’ == valid day # string abbreviations from this list: Mon Tue Wed Thu Fri Sat Sun weekmask = "Mon Tue Wed Thu Fri" # any amount of whitespace is allowed.1 >>> np.datetime64(’2011-07-18’)) >>> np. 0] # list or other sequence. abbreviations are case-sensitive. 0. and silently allows invalid input without raising errors. with a few convenience extensions.busday_count(np. # Length of the sequence must be exactly 7. 1.6 and 1.6 is very liberal in what it accepts.busday_count(np. weekmask = [1.NumPy Reference.8. np.datetime64(’2011-07-11’)) -5 If you have an array of datetime64 day values. and you want a count of how many of them are valid dates.is_busday(a)) 5 Custom Weekmasks Here are several examples of custom weekmask values.datetime64(’2011-07-11’). Release 1.datetime64(’2011-07-11’).

’garbage’ raises an exception >>> np.6. handles this case correctly 1.datetime64(’NaT’) # NumPy 1.7.datetime64(’1979-03-22’). ignores invalid part of string >>> np.1. ’h’) Traceback (most recent call last): File "<stdin>". ’garbage’ produces today’s date >>> np.9.6.6.0. reads ISO 8601 strings w/o TZ as UTC >>> np. raises error for invalid input >>> np.6.0 >>> np. line 1.datetime64(’1979-03-2corruptedstring’) Traceback (most recent call last): File "<stdin>".dtype dtype(’<M8[D]’) # NumPy 1.0.’h’) # NumPy 1.datetime64(’garbage’) Traceback (most recent call last): File "<stdin>".datetime64(’nat’) 2012-04-30 00:00:00 # NumPy 1.0.array([’1979-03-22T12:00’].1.NumPy Reference.datetime64(’1979-03-22T19:00’.7. dtype=datetime64[h]) >>> np. Release 1.1.datetime64(’nat’) numpy. dtype=’M8[h]’) array([1979-03-22 00:00:00].6. dtype=’datetime64[h]’) # NumPy 1.7.array([’1979-03-22T19:00’].datetime64(’1979-03-22’) numpy.7.datetime64(’1979-03-22’). ’nat’ produces not-a-time >>> np. doesn’t parse all ISO 8601 strings correctly >>> np.array([’1979-03-22T12’]. Datetimes and Timedeltas 429 . reads ISO 8601 strings w/o TZ as local (ISO specifies this) >>> np.1.7.6.7. in <module> ValueError: Error parsing datetime string "garbage" at position 0 # NumPy 1. ’nat’ produces today’s date >>> np.1. dtype=’M8[h]’) array([’1979-03-22T19-0500’].datetime64(’1979-03-22T19:00’.0. in <module> ValueError: Error parsing datetime string "1979-03-2corruptedstring" at position 8 # NumPy 1. ’h’) numpy. dtype=’M8[h]’) array([1979-03-22 19:00:00]. dtype=’M8[h]’) array([1979-03-22 12:00:00].1.7.datetime64(’1979-03-22T19:00-0500’.0. line 1.1 # NumPy 1. unit default microseconds >>> np.datetime64(’1979-03-22’) # NumPy 1. in <module> TypeError: function takes at most 1 argument (2 given) # NumPy 1. dtype=datetime64[h]) # NumPy 1.0. unit in scalar constructor >>> np.0.8.array([’1979-03-22T19:00’]. line 1.1.datetime64(’garbage’) 2012-04-30 00:00:00 # NumPy 1. unit of days detected from string >>> np. can’t specify unit in scalar constructor >>> np.7.dtype dtype(’datetime64[us]’) # NumPy 1. dtype=datetime64[h]) # NumPy 1.6.datetime64(’1979-03-2corruptedstring’) 1979-03-02 00:00:00 # NumPy 1.

0.7. the representation is scaled accordingly >>> np. promotes to higher-resolution unit >>> a = np. dtype=’M8[us]’) >>> b = np.array([’1979-03-22’].array([3*60*60*1000000]. dtype=’M8[D]’) array([’1979-03-22’]. dtype=’datetime64[us]’) 430 Chapter 1.array([’1979-03-22T12:00’]. dtype=datetime64[M]) # NumPy 1. dtype=’m8[us]’) >>> a + b array([1979-03-22 15:00:00].6 implementation of datetime does not convert between units correctly. dtype=’M8[h]’) array([’1979-03-22T12-0500’]. dtype=’M8[h]’) >>> b = np.1 >>> np.: # NumPy 1. dtype=’datetime64[h]’) Unit Conversion The 1. dtype=datetime64[us]) # NumPy 1. the representation value is untouched >>> np.array([’1979-03-22’]. dtype=’m8[m]’) >>> a + b array([1970-01-01 00:00:00.1.array([3*60*60*1000000]. dtype=datetime64[us]) # NumPy 1. dtype=’m8[m]’) >>> a + b array([’1979-03-22T15:00-0500’]. dtype=’M8[h]’) array([’1979-03-22T12-0500’]. dtype=’M8[D]’). Release 1.array([3*60]. dtype=’datetime64[m]’) # NumPy 1. dtype=’datetime64[M]’) Datetime Arithmetic The 1.array([3*60]. dtype=’datetime64[D]’) >>> np.6 implementation of datetime only works correctly for a small subset of arithmetic operations.array([’1979-03-22T12’].080988]. dtype=’M8[us]’) >>> b = np. dtype=’M8[h]’) >>> b = np. dtype=datetime64[D]) >>> np. dtype=’m8[us]’) >>> a + b array([’1979-03-22T15:00:00.000000-0500’]. produces invalid results if units are incompatible >>> a = np.array([’1979-03-22T12:00’].array([’1979-03-22’].astype(’M8[M]’) array([’1979-03’].array([’1979-03-22T12’].7.1.0 >>> a = np.NumPy Reference.: # NumPy 1.6.6.1.array([’1979-03-22’].array([’1979-03-22T12:00’].0. dtype=’datetime64[h]’) >>> np.array([’1979-03-22T12’].8.astype(’M8[M]’) array([2250-08-01 00:00:00].7. dtype=’M8[D]’) array([1979-03-22 00:00:00].6. arithmetic works if everything is microseconds >>> a = np. dtype=’M8[D]’). Array objects . Here we show some simple cases.

type casting. or has value exactly 1. and several other standard features.6). 4. then a. 3. i. Example If a.6) array where a[:. Broadcasting can be understood by four rules: 1. the first data entry in that dimension will be used for all calculations along that dimension. and • a acts like a (5. All input arrays with ndim smaller than the input array of largest ndim. b. universal functions are instances of the numpy. Standard broadcasting rules are applied so that inputs not sharing exactly the same shapes can still be usefully operated on. for example.shape is (6. Broadcasting is used throughout NumPy to decide how to handle disparately shaped arrays.1 Broadcasting Each universal function takes array inputs and produces array outputs by performing the core function element-wise on the inputs. The arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2. In other words. 2. 3. The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1. supporting array broadcasting. b..CHAPTER TWO UNIVERSAL FUNCTIONS (UFUNC) A universal function (or ufunc for short) is a function that operates on ndarrays in an element-by-element fashion. • b acts like a (5. 2. Many of the built-in functions are implemented in compiled C code. A set of arrays is called “broadcastable” to the same shape if the above rules produce a valid result.) and d. In Numpy. have 1’s prepended to their shapes..e. If an input has a dimension size of 1 in its shape.6) array where b[0.0] is broadcast to the other columns. The size in each dimension of the output shape is the maximum of all the input sizes in that dimension. 2. -.1). 431 . An input can be used in the calculation if its size in a particular dimension either matches the output size in that dimension. but ufunc instances can also be produced using the frompyfunc factory function.. c. all arithmetic operations (+.shape is (5.:] is broadcast to the other rows. and d are all broadcastable to dimension (5. .ufunc class. one of the following is true: 1. That is. the stepping machinery of the ufunc will simply not step along that dimension (the stride will be 0 for that dimension).shape is () so that d is a scalar. c.) between ndarrays broadcast the arrays before operation. 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.6). The arrays all have exactly the same shape.shape is (1. *.

The default size of a buffer is 10. swapped data. • d acts like a (5.6) array where c[:] is broadcast to every row. it is called so metadata may be determined based on the context of the ufunc (the context consisting of the ufunc itself.6) array where the single value is repeated. these registers will be regularly checked during calculation. Error handling is controlled on a per-thread basis. The default __array_priority__ of the ndarray is 0.0.NumPy Reference. divide.8. Set the floating-point error callback function or log object. and can be configured using the functions seterr([all. output will be cast to the data-type(s) of the provided output array(s). the returned ndarray result will be passed to that method just before passing control back to the caller. those misbehaved or incorrectly-typed arrays will be copied before the calculation proceeds. and data that has to be converted from one data type to another. and finally. 2. All ufuncs can also take output arguments. Finally.setbufsize(size) Set the size of the buffer used in ufuncs. Whenever buffer-based calculation would be needed.0. Chapter 2. and the default __array_priority__ of a subtype is 1. if the class also has an __array_wrap__ method. over. 2.0. The size of internal buffers is settable on a per-thread basis. if the class also has an __array_prepare__ method. but all input arrays are smaller than the buffer size. If available on your platform. numpy. Universal functions (ufunc) . if all input arguments are not ndarrays. A simple interface for setting this variable is accessible using the function setbufsize(size) Set the size of the buffer used in ufuncs. 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. Matrices have __array_priority__ equal to 10.6) array and therefore like a (5. under. invalid]) seterrcall(func) 432 Set how floating-point errors are handled. If a class with an __array__ method is used for the output. results will be written to the object returned by __array__. Parameters size : int Size of buffer. Then. Adjusting the size of the buffer may therefore alter the speed at which ufunc calculations of various sorts are completed.3 Use of internal buffers Internally. All output arrays will be passed to the __array_prepare__ and __array_wrap__ methods of the input (besides ndarrays. 2. the arguments passed to the ufunc.) The array object returned by __array_prepare__ is passed to the ufunc for computation.2 Output type determination The output of the ufunc (and its methods) is not necessarily an ndarray. buffers are used for misaligned data. and the ufunc domain. If necessary.4 Error handling Universal functions can trip special floating-point status registers in your hardware (such as divide-by-zero).000 elements. Release 1. and scalars) that defines it and has the highest __array_priority__ of any other input to the universal function.1 • c acts like a (1.

‘print’.4. optional Treatment for division by zero. ‘log’}. ‘log’}. typically indicates that a NaN was produced. ‘warn’. Release 1. ‘call’. invalid : {‘ignore’. •Overflow: result too large to be expressed. under : {‘ignore’.NumPy Reference.seterr(all=None. ‘print’. Error handling 433 . ‘raise’. ‘call’. The default is not to change the current behavior. ‘print’. ‘warn’. optional Treatment for floating-point overflow. ‘print’. ‘warn’. ‘log’}. 2. over : {‘ignore’. under=None. • call: Call a function specified using the seterrcall function. • raise: Raise a FloatingPointError. ‘raise’. Parameters all : {‘ignore’. errstate Notes The floating-point exceptions are defined in the IEEE 754 standard [1]: •Division by zero: infinite result obtained from finite numbers. • warn: Print a RuntimeWarning (via the Python warnings module). ‘raise’. ‘call’.8. ‘log’}. ‘call’. Note that operations on integer scalar types (such as int16) are handled like floating point. •Invalid operation: result is not an expressible number. ‘warn’. optional Treatment for invalid floating-point operation. ‘raise’. and are affected by these settings. ‘log’}. geterr. over=None. ‘call’. •Underflow: result so close to zero that some precision was lost. • log: Record error in a Log object specified by seterrcall. See Also: seterrcall Set a callback function for the ‘call’ mode. geterrcall.1 numpy. ‘print’. optional Treatment for floating-point underflow. invalid=None) Set how floating-point errors are handled. divide : {‘ignore’. Returns old_settings : dict Dictionary containing the old settings. divide=None. ‘warn’. ‘raise’. optional Set treatment for all types of floating-point errors at once: • ignore: Take no action when the exception occurs. • print: Print a warning directly to stdout.

See Also: seterr.8. There are two ways to capture floating-point error messages.seterr(over=’raise’) {’over’: ’ignore’. and the second is the status flag. “under”.NumPy Reference. ’divide’: ’ignore’. “over”. its write method should take one argument. whose least-significant bits indicate the status: [0 0 0 0 invalid over under invalid] In other words. ’divide’: ’ignore’. Returns h : callable. The first is to set the error-handler to ‘call’. line 1.1 Examples >>> old_settings = np.seterr(all=’ignore’) #seterr to known value >>> np. ’invalid’: ’ignore’.seterr(**old_settings) # reset to default {’over’: ’raise’.int16(32000) * np. a string. ’under’: ’print’} >>> np.seterr(all=’warn’. set the function to call using this function. ’under’: ’ignore’} >>> np.int16(3) 30464 >>> old_settings = np. geterr. using seterr.seterrcall(func) Set the floating-point error callback function or log object. Parameters func : callable f(err. flags = divide + 2*over + 4*under + 8*invalid. Universal functions (ufunc) . geterrcall Examples Callback upon error: 434 Chapter 2. ’invalid’: ’ignore’. or “invalid”). ’invalid’: ’print’. log instance or None The old error handler. Release 1. The second is to set the error-handler to ‘log’. using seterr. The call function takes two arguments.int16(32000) * np. If an object is provided. Then.int16(3) Warning: overflow encountered in short_scalars 30464 numpy.int16(32000) * np. ’under’: ’ignore’} >>> np. The first is the type of error (one of “divide”.int16(3) Traceback (most recent call last): File "<stdin>".geterr() {’over’: ’print’. The flag is a byte. 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). ’divide’: ’print’. in <module> FloatingPointError: overflow encountered in short_scalars >>> old_settings = np. Floating-point errors then trigger a call to the ‘write’ method of the provided object.seterr(all=’print’) >>> np. over=’raise’) >>> np.

msg): . 2.seterrcall(err_handler) >>> save_err = np. At the core of every ufunc is a one-dimensional strided loop that implements the actual function for a specific type combination. Inf. Inf]) >>> np.. Inf. The ufunc machinery uses this list to determine which inner loop to use for a particular case.. See the functions result_type. ’under’: ’log’} 2.5 Casting Rules Note: In NumPy 1.. with flag 1 array([ Inf.seterr(all=’call’) >>> np. Inf]) >>> np.seterr(**save_err) {’over’: ’call’. flag) . If an implementation for the input types cannot be found.> >>> np. and min_scalar_type for more details. ’under’: ’call’} Log error message: >>> class Log(object): .. When a ufunc is created.array([1. flag): . print "Floating point error (%s)...array([1.. with flag %s" % (type.seterr(all=’log’) >>> np.8. promote_types.seterrcall(saved_handler) <__main__.1 >>> def err_handler(type. def write(self.> >>> np. >>> log = Log() >>> saved_handler = np.” The first one it finds in its internal list of loops is selected and performed. 3]) / 0. a type promotion API was created to encapsulate the mechansim for determining output types.Log object at 0x.6. print "LOG: %s" % msg . 2. >>> saved_handler = np. after all necessary type casting. 3]) / 0. it is given a static list of inner loops and a corresponding list of type signatures over which the ufunc operates. ’divide’: ’call’.0 LOG: Warning: divide by zero encountered in divide array([ Inf. 2. ’divide’: ’log’. Recall that internal copies during ufuncs (even for casting) are limited to the size of an internal buffer (which is user settable)..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).5. 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. Casting Rules 435 .. Release 1.seterrcall(log) >>> save_err = np.0 Floating point error (divide by zero)..0. ’invalid’: ’log’.seterr(**save_err) {’over’: ’log’..seterrcall(saved_handler) <function err_handler at 0x.. ’invalid’: ’call’.NumPy Reference.. then the algorithm searches for an implementation with a type signature to which all of the inputs can be cast “safely. You can inspect the ..

a universal function could be defined that works with floating-point and integer values.typecodes[’All’]) b h i l q p B H I L Q P e f d g F D G S U V O 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 0 0 1 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 M 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 m 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 You should note that. are interpreted 436 Chapter 2. Release 1. >>> X ? ? 1 b 0 h 0 i 0 l 0 q 0 p 0 B 0 H 0 I 0 L 0 Q 0 P 0 e 0 f 0 d 0 g 0 F 0 D 0 G 0 S 0 U 0 V 0 O 0 M 0 m 0 def print_table(ntypes): print ’X’. totype).e. This rule enables you to use scalar constants in your code (which.NumPy Reference. for char in ntypes: print char. .. >>> .. the casting rules are essentially implemented by the question of when a data type can be cast “safely” to another data type... . col)). and ‘V’ types cannot be operated on by ufuncs...8. ‘U’. .. The answer to this question can be determined in Python with a function call: can_cast(fromtype.. as Python types. while included in the table for completeness. . Figure Code segment showing the “can cast safely” table for a 32-bit system. Also.. Thus. resulting in a slightly altered table.1 Note: Universal functions in NumPy are flexible enough to have mixed type signatures. Universal functions (ufunc) . for example.. You can generate this table for your system with the code given in the Figure. note that on a 32-bit system the integer types may have different sizes. By the above description.. .. .. See ldexp for an example.can_cast(row. 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. The Figure below shows the results of this call for the 24 internally supported types on the author’s 64-bit system. . for col in ntypes: print int(np. under a different hierarchy in the data-type hierarchy) than the array. the ‘S’.... print print_table(np.. print for row in ntypes: print row.

7. Passing them here circumvents that look up and uses the low-level specification provided for the error mode. order New in version 1. If set to false. this argument will default to ‘same_kind’. If the loop specified does not exist for the ufunc. As part of this transition. Overrides the dtype of the calculation and output arrays. Provides a policy for what kind of casting is permitted. This may be 2. the error mode integer. values of False indicate to leave the value in the output alone. or a special signature string indicating the input and output types of a ufunc. a tuple of data-types. 2.6. ‘safe’.6 ufunc 2.1 accordingly in ufuncs) without worrying about whether the precision of the scalar constant will cause upcasting on your large (small precision) array. then a TypeError is raised.6. ‘A’ means F-contiguous if the inputs are F-contiguous and not also not C-contiguous. Defaults to ‘K’. Similar to sig. or 3 specifying the ufunc buffer-size. and the error callback function.NumPy Reference. this defaults to ‘unsafe’. but not under the ‘same_kind’ rules. A list of available signatures is provided by the types attribute of the ufunc object. not a subtype. casting New in version 1. See can_cast for explanations of the parameter values. For compatibility with previous versions of NumPy. C-contiguous otherwise. Accepts a boolean array which is broadcast together with the operands. dtype New in version 1. This argument allows you to provide a specific signature for the 1-d loop to use in the underlying calculation. Normally. out New in version 1.6.6. subok New in version 1. 2. extobj a list of length 1.6. ‘same_kind’. 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. starting in version 1. Values of True indicate to calculate the ufunc at that position. ‘equiv’. Specifies the calculation iteration order/memory layout of the output array. Release 1. This keyword argument lets you bypass that search and choose a particular loop. Normally. ufuncs will produce a DeprecationWarning for calls which are allowed under the ‘unsafe’ rules.1 Optional keyword arguments All ufuncs take optional keyword arguments. ‘C’ means the output should be C-contiguous. these values are looked up in a thread-specific dictionary. where New in version 1. Most of these represent advanced usage and will not typically be used. Defaults to true. The first output can provided as either a positional or a keyword parameter.7. the output will always be a strict array. ‘F’ means F-contiguous. sig Either a data-type. May be ‘no’. or ‘unsafe’. ufunc 437 . In a future version of numpy. and ‘K’ means to match the element ordering of the inputs as closely as possible.6.8.6.

nout The number of outputs. The number of outputs.nout np. this will always be (at least) 1. Notes Since all ufuncs can take output arguments.types ufunc. The number of types.nin np.nin ufunc.6.nin np.2 Attributes There are some informational attributes that universal functions possess. Universal functions (ufunc) .identity The number of inputs.exp.power. ufunc. Examples >>> 2 >>> 2 >>> 2 >>> 1 np. The second part of the docstring is provided at creation time and stored with the ufunc.multiply. Data attribute containing the number of arguments the ufunc treats as input. __name__The name of the ufunc.power. and the number of inputs. Examples >>> 1 >>> 1 >>> 1 >>> 1 np.exp. 438 Chapter 2. The number of arguments.nin The number of inputs. Data attribute containing the number of arguments the ufunc treats as output.nout np.add.ntypes ufunc. The identity value.nout np.nin ufunc. 2.nargs ufunc.add. Returns a list with types grouped input->output.1 useful. ufunc.multiply. the name. None of the attributes can be set. as an optimization for calculations requiring many ufunc calls on small arrays in a loop.nout ufunc. Release 1.nargs The number of arguments. __doc__ A docstring for each ufunc.NumPy Reference.8.nin np. for example.nout ufunc. The first part of the docstring is dynamically generated from the number of outputs.

’gg->g’. ’LL->L’. ’gg->g’. ’ll->l’. ’II->I’. ’HH->H’. Release 1. ’DD->D’. ’ll->l’. ’dd->d’.8. ’OO->O’] >>> np. ’BB->B’. ’bb->b’.types Returns a list with types grouped input->output.add. ufunc 439 .remainder. ’FF->F’.ntypes np.power. Notes Typically this value will be one more than what you might expect because all ufuncs take the optional “out” argument.NumPy Reference. ’hh->h’.nargs np. ’LL->L’.ntypes The number of types.nargs np.nargs ufunc. See Also: numpy. ’BB->B’. ’QQ->Q’. The number of numerical NumPy types .ufunc. ’OO->O’] 2.exp.types [’??->?’.ntypes np.of which there are 18 total . ’dd->d’.add.multiply.exp. ’HH->H’.nargs np. ’bb->b’.ntypes Examples >>> np.ntypes np. ’hh->h’. ’qq->q’. ’qq->q’.ntypes ufunc.ufunc. ’II->I’.multiply. ’ii->i’. See Also: numpy.power. ’GG->G’. ’GG->G’. including optional ones. ’FF->F’. ’ii->i’. Data attribute listing the data-type “Domain-Range” groupings the ufunc can deliver.on which the ufunc can operate. ’QQ->Q’.types [’??->?’.ntypes np. ’DD->D’.multiply. ’ff->f’.add.6. Examples >>> 3 >>> 3 >>> 3 >>> 2 np. The data-types are given using the character codes. ’ff->f’.1 Data attribute containing the number of arguments the ufunc takes.types Examples >>> 18 >>> 18 >>> 17 >>> 7 >>> 14 np.

identity The identity value. out. Release 1. Ufuncs also have a fifth method that allows in place operations to be performed using fancy indexing. ’LL->L’. The dtype keyword allows you to alter the data type over which the reduction takes place (and therefore the type of the output). ’hh->h’. If it does not. ’OO->O’] >>> np. ’DD->D’. these methods only make sense on ufuncs that take two input arguments and return one output argument. Accumulate the result of applying the operator to all elements. Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘ ufunc. This commonly happens if you have an array of single-byte integers. ’g->g’.remainder. dtype. ’D->D’.power.3 Methods All ufuncs have four methods. ’QQ->Q’. Thus. ’d->d’.accumulate(array[. out]) ufunc.at(a. axis=0. The dtype keyword allows you to manage a very common problem that arises when naively using {op}. Examples >>> np. if it has one. ’ll->l’. ’OO->O’] ufunc. then if the input type is an integer (or Boolean) data-type and smaller than the size of the int_ data type. and the arrays must all have dimension >= 1. Performs a (local) reduce with specified slices over a single axis. but the result does not fit into the data type of the array.reduce(a[.8. ’GG->G’.reduce.types [’bb->b’.NumPy Reference.identity None 2. The reduce-like methods all take an axis keyword and a dtype keyword. indices[. but must be an integer. ’ii->i’. ’QQ->Q’. B) ufunc. The responsibility of altering the reduce type is mostly up to you. Data attribute containing the identity element for the ufunc. ’qq->q’. ’HH->H’. ’O->O’] >>> np. ’hh->h’.power. you can ensure that the output is a data type with precision large enough to handle your output. axis. axis. Universal functions (ufunc) . ’HH->H’.multiply. ’LL->L’. keepdims=False) 440 Chapter 2. ufunc.exp. indices[.identity 1 >>> np. b]) Reduces a‘s dimension by one. ’dd->d’. ’II->I’. Sometimes you may have an array of a certain data type and wish to add up all of its elements. by applying ufunc along one axis.identity 0 >>> np. Apply the ufunc op to all pairs (a. axis. ’FF->F’. dtype. ’BB->B’.identity 1 >>> print np.types [’bb->b’. out]) ufunc. it will be internally upcast to the int_ (or uint) data-type.6. dtype=None. out=None. ’gg->g’. ’dd->d’. ’gg->g’. ’ff->f’. ’BB->B’. However.add. ’G->G’. so the fancy index can list an item more than once and the operation will be performed on the result of the previous operation for that item. ’F->F’.1 >>> np. keepdims]) ufunc.outer(A. There is one exception: if no dtype is given for a reduction on the “add” or “multiply” operations. the attribute value is None.types [’f->f’. ’ii->i’. ’qq->q’. ’II->I’. ’ff->f’. dtype.exp. b) with a in A and b in B. The axis keyword specifies the axis of the array over which the reduction will take place and may be negative.reduceat(a. No buffering is used on the dimensions where fancy indexing is used. ’ll->l’.reduce(a. Attempting to call these methods on other ufuncs will cause a ValueError.

For a one-dimensional array. [[4. .shape = (N0 . a reduction is performed over all the axes. axis = i)[k0 . If out was supplied. optional A location into which the result is stored. . in which case it counts from the last to the first axis.6.0.2.reshape((2.. Let a. . 2. kM −1 ] = the result of iterating j over range(Ni ).reduce() is equivalent to sum(). axis may be negative.. Parameters a : array_like The array to act on. With this option. a reduction is performed on multiple axes. Examples >>> np. [2.. Defaults to the data-type of the output array if this is provided.. keepdims : bool..arange(8). cumulatively applying ufunc to each a[k0 ..NumPy Reference.. Ni .2)) >>> X array([[[0.3. ki−1 . the axes which are reduced are left in the result as dimensions with size one. If this is None. NM −1 ). If this is a tuple of ints. optional If this is set to True.5]) 30 A multi-dimensional array example: >>> X = np. ki+1 .reduce([2. axis : None or int or tuple of ints. For operations which are either not commutative or not associative. add. dtype : data-type code.reduce(a. instead of a single axis or all the axes as before. Then uf unc. r is a reference to it. by applying ufunc along one axis. ufunc 441 . . ki−1 .. 5]. the result will broadcast correctly against the original arr. ki+1 . The ufuncs do not currently raise an exception in this case.. or the data-type of the input array if no output array is provided. j.. New in version 1. a freshly-allocated array is returned.. A[i]) return r For example. optional The type used to represent the intermediate results.multiply. doing a reduction over multiple axes is not well-defined.1 Reduces a‘s dimension by one. Returns r : ndarray The reduced array... If not provided. 1]. The default (axis = 0) is perform a reduction over the first dimension of the input array. optional Axis or axes along which a reduction is performed. reduce produces results equivalent to: r = op. 3]].8. . but will likely do so in the future. out : ndarray. ..identity # op = ufunc for i in range(len(A)): r = op(r.7. kM −1 ]. Release 1.

If not provided a freshly-allocated array is returned.reduce(X.cumsum(). array([[ 1.add.reduce(X. accumulate produces results equivalent to: r = np. r is a reference to out. 4]. axis : int. see Examples below) so repeated use is necessary if one wants to accumulate over multiple axes. Release 1. default is zero. 10]) 442 Chapter 2. 6]. dtype=None. or the the data-type of the input array if no output array is provided. For a one-dimensional array.add. Defaults to the data-type of the output array if such is provided. Parameters array : array_like The array to act on. 6]. optional The axis along which to apply the accumulation. 5]. 5]) array([ 2.accumulate([2. add. 13]]) 0) # confirm: default axis value is 0 1) 2) ufunc. optional The data-type used to represent the intermediate results. [ 8.accumulate(array. 3. Returns r : ndarray The accumulated values. 10]]) >>> np. 12]]) >>> np. array([[ 2. For a multi-dimensional array. A[i]) r[i] = t return r elements For example. out : ndarray. [10. Universal functions (ufunc) .1 [6.add. array([[ 4. 5.8.empty(len(A)) t = op.identity # op = the ufunc being applied to A’s for i in range(len(A)): t = op(t. If out was supplied. accumulate is applied along only one axis (axis zero by default. 7]]]) >>> np. axis=0. Examples 1-D array examples: >>> np.add. [ 8. dtype : data-type code.reduce(X.reduce(X) array([[ 4. [ 9.add. 10]]) >>> np.accumulate() is equivalent to np. out=None) Accumulate the result of applying the operator to all elements. optional A location into which the result is stored.NumPy Reference.

comma separated (not colon).accumulate([2. through rows: >>> np. 30]) 2-D array examples: >>> I = np..]. 2. specifying slices to reduce. Parameters a : array_like The array to act on. dtype : data-type code. [ 1.].reduceat(a. Release 1. 1) array([[ 1.eye(2) >>> I array([[ 1.shape[axis]. If not provided a freshly-allocated array is returned. 3. indices[i+1] = a. out=None) Performs a (local) reduce with specified slices over a single axis. [ 1.accumulate(I. it becomes the i-th column).. Defaults to the data type of the output array if this is provided.]]) ufunc.reduce(a[indices[i]:indices[i+1]]). 0. 0) array([[ 1.]]) >>> np.]]) Accumulate along axis 0 (rows). 1.. reduceat computes ufunc..add. indices. or the data type of the input array if no output array is provided..add. 1. for example. and may be larger than a (this happens if len(indices) > a..add. [ 0.NumPy Reference. 1.6. There are two exceptions to this: •when i = len(indices) . The shape of the output depends on the size of indices.1 >>> np.accumulate(I. the i-th generalized “row” is simply a[indices[i]]. 6. For i in range(len(indices)). axis=0. optional The type used to represent the intermediate results.e.shape[axis]). which becomes the i-th generalized “row” parallel to axis in the final result (i. 0. in a 2-D array.1 (so for the last index). optional A location into which the result is stored.]. but if axis = 1. 5]) array([ 2.. ufunc 443 .]]) Accumulate along axis 1 (columns)..multiply. 0. [ 0.accumulate(I) # no axis specified = axis zero array([[ 1. •if indices[i] >= indices[i + 1].8. optional The axis along which to apply the reduceat. 1. 1. indices : array_like Paired indices. dtype=None. down columns: >>> np. if axis = 0. out : ndarray. it becomes the i-th row.]. axis : int..

outer(A. [0.].. [ 24. indices[1::2] = range(1.. 3]. [ 4. Then the result..1).linspace(0. 16).reduceat(x. 1.]. [ 2184.4) >>> x array([[ 0. 14.5. 1.]. 13.outer(A. 11.].reduceat(a. 28.... N = B.].. len(a)). Don’t be fooled by this attribute’s name: reduceat(a) is not necessarily smaller than a. [ 12. B) Apply the ufunc op to all pairs (a. 15.arange(8). [ 120..1) with a zero placed in every other element: indices = zeros(2 * len(a) . 7.NumPy Reference.. 11. 3.. Release 1. 6.ndim. 32. 9.. 14. 2. 7... If out was supplied.6. 1) array([[ 0....]. [ 4. 18]) A 2-D example: >>> x = np.add. indices)[::2] where indices is range(len(array) ..7])[::2] array([ 6. b) with a in A and b in B.reduceat(np...].reduceat(x.multiply. 18.. [ 720. 1.]]) # reduce such that result has the following two columns: # [col1 * col2 * col3. Examples To take the running sum of four successive values: >>> np. Universal functions (ufunc) .]. col4] >>> np. 13.. Notes A descriptive example: If a is 1-D.reshape(4.. 15. 3. 2. [ 8.8. the function ufunc.]]) ufunc.. 11. B) is an array of dimension M + N 444 Chapter 2. array([[ 12. 0]) 21.. 5. 9.. 5. 36. 10. Let M = A. 10.[0. 15. 6.. 10. 7. [0. r is a reference to out...accumulate(a) is the same as ufunc. of op.]]) # # # # # # reduce such that the result has the following five rows: [row1 + row2 + row3] [row4] [row2] [row3] [row1 + row2 + row3 + row4] >>> np. 3. 14. 3. C. [ 12.4.. 15. [ 8.]. 15..ndim.add.].1 Returns r : ndarray The reduced values.. 2.

. 3]. 3].at(a. 2. jN −1 ]) For A and B one-dimensional. 16]]. 12. New in version 1. . 2.multiply. 18]]) A multi-dimensional example: >>> A = np. C (2.NumPy Reference. 4]]) >>> B. B[j0 . 4) >>> C = np. 4. [[[ 4.6. 5. 8]].. 24]]]]) ufunc. [4. . this is equivalent to: r = empty(len(A). For example.j] = op(A[i]. 20]]. 3) >>> B = np.at(a.outer Examples >>> np. j0 . whereas add. B) >>> C. 2. 10. 3. 4) array([[[[ 1.shape (2. jN −1 ] = op(A[i0 . iM −1 ]. 6.8. 2. b=None) Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘indices’. [ 8. 12]]].array([[1.. except that results are accumulated for elements that are indexed more than once. 6]]) >>> A.array([[1.0. ... [[ 5. 10. 6]) array([[ 4. 1. 2. 3.1 such that: C[i0 . [[ 3.outer([1. 5. For addition ufunc.shape. 9.. [0. 1) will increment the first element twice. 3.0].0]] += 1 will only increment the first element once because of buffering. 15. 8.. this method is equivalent to a[indices] += b.outer(A. [4... 6. 5. a[[0. [[ 6.. 4]]. 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. 18.len(B)) for i in range(len(A)): for j in range(len(B)): r[i. indices. Release 1.multiply..8.. 6]. [12. 12]. 15.. 12. ufunc 445 . [[ 2. iM −1 .shape (1.

b) >>> print(a) array([2. 2]. 1]. 4]) Add items 0 and 1 in first array to second array. Some of these ufuncs are called automatically on arrays when the relevant infix notation is used (e.NumPy Reference.array([1. b) is called internally when a + b is written and a or b is an ndarray). indices can be a tuple of array like index objects or slice objects. add(a. 2. indices : array_like or tuple Array like index object or slice object for indexing into first operand.add. 4]) 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. [0. Universal functions (ufunc) . 446 Chapter 2. 2. 2. Note: The ufunc still returns its output(s) even if you use the optional output argument(s). 3. If first operand has multiple dimensions. 4]) >>> np.at(a. Therefore. 3. Nevertheless. 1]) >>> print(a) array([-1. 4. 5.8.g. 2. [0. each ufunc will be described as if acting on a set of scalar inputs to return a set of scalar outputs. 4]) >>> b = np.array([1.array([1.negative. One should use dtype to increase the size of the data-type over which reduction takes place.at(a. 1. 4]) >>> np. 3. Operand must be broadcastable over first operand after indexing or slicing. 2.at(a. 1) >>> print(a) array([2. 3. Examples Set items 0 and 1 to their negative values: >>> a = np. [0. covering a wide variety of operations. 3. 4]) Increment items 0 and 1. b : array_like Second operand for ufuncs requiring two operands.7 Available ufuncs There are currently more than 60 universal functions defined in numpy on one or more types. Release 1.1 Parameters a : array_like The array to perform in place operation on. 3. Recall that each ufunc operates element-by-element.add.. -2.array([1. 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. and store results in first array: >>> a = np. 2]) >>> np. and increment item 2 twice: >>> a = np.

x2[. out]) arctan(x[. out]) exp2(x[. out]) cos(x[. out]) tan(x[. Return the element-wise square of the input. Trigonometric inverse tangent. G += C. out]) log(x[. C. element-wise. Tip: The optional output arguments can be used to help you save memory for large calculations. out]) subtract(x1. element-wise. Logarithm of the sum of exponentiations of the inputs. out]) conj(x[. G) which is the same as G = A * B. Divide arguments element-wise. 2. Subtract arguments. out]) absolute(x[. out]) arcsin(x[. x2[. Calculate 2**p for all p in the input array. x2[. x2[. x2[. Return the complex conjugate. the expression G = a * b + c is equivalent to t1 = A * B. out]) ones_like(a[. x2[. Compute tangent element-wise. element-wise. order. out]) true_divide(x1. x2[.1 for all elements in the array. out]) floor_divide(x1. The ratio of degrees to radians is 180◦ /π. Cosine element-wise. For example. out]) arctan2(x1. element-wise. Return the positive square-root of an array. out]) divide(x1.1 Math operations add(x1. out]) arccos(x[. out]) fmod(x1. out]) mod(x1. out]) expm1(x[. out]) negative(x[. x2[. del t1. Trigonometric inverse cosine. Inverse sine. out]) multiply(x1. Element-wise arc tangent of x1/x2 choosing the quadrant correctly. add(G. out]) log1p(x[. element-wise.7. x2[. Return an array of ones with the same shape and type as a given array. Return the natural logarithm of one plus the input array. Returns an element-wise indication of the sign of a number. element-wise. Return element-wise remainder of division. Logarithm of the sum of exponentiations of the inputs in base-2. dtype. Calculate the exponential of all elements in the input array. Returns a true division of the inputs. Available ufuncs Trigonometric sine.1 2. Return element-wise remainder of division. Calculate exp(x) . x2[.7.8. out]) remainder(x1.2 Trigonometric functions All trigonometric functions use radians when an angle is called for. out]) log10(x[. sin(x[. It will be more quickly executed as G = A * B. Round elements of the array to the nearest integer. Calculate the absolute value element-wise. out]) 2. out]) log2(x[. out]) square(x[. Return the element-wise remainder of division. G = T1 + C. Release 1. x2[. element-wise. out]) reciprocal(x[. element-wise. out]) sqrt(x[. out]) logaddexp2(x1. Numerical negative. First array elements raised to powers from second array. complicated expressions can take longer than absolutely necessary due to the creation and (later) destruction of temporary calculation spaces. out]) rint(x[. Natural logarithm.NumPy Reference. subok]) Add arguments element-wise. x2[. Return the largest integer smaller or equal to the division of the inputs. If your arrays are large. element-wise. element-wise. out]) sign(x[. out]) power(x1. Return the base 10 logarithm of the input array.7. Continued on next page 447 . out]) exp(x[. element-wise. out]) logaddexp(x1. x2[. Base-2 logarithm of x. element-wise. Multiply arguments element-wise. element-wise. element-wise. Return the reciprocal of the argument.

out]) bitwise_xor(x1. x2[. out]) less(x1.7. out]) greater_equal(x1. Inverse hyperbolic cosine. Chapter 2. out]) arcsinh(x[.1 hypot(x1. out]) bitwise_or(x1.7. out]) 448 Element-wise maximum of array elements. out]) Table 2. element-wise. 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. or bit-wise NOT. out]) equal(x1. Compute the bit-wise XOR of two arrays element-wise. Shift the bits of an integer to the right. element-wise. Compute bit-wise inversion. out]) logical_xor(x1. out]) left_shift(x1. out]) deg2rad(x[. Return (x1 == x2) element-wise. x2[. Convert angles from degrees to radians. Hyperbolic cosine. x2[. out]) tanh(x[. out]) invert(x[. out]) cosh(x[. x2[. Return the truth value of (x1 =< x2) element-wise. out]) arccosh(x[. element-wise. x2[. x2[. maximum(x1. x2[. Compute the truth value of NOT x element-wise. Warning: Do not use the Python keywords and and or to combine logical array expressions. out]) less_equal(x1. out]) logical_not(x[. return its hypotenuse. Return the truth value of (x1 >= x2) element-wise. out]) right_shift(x1. out]) sinh(x[.3 Bit-twiddling functions These function all require integer arguments and they manipulate the bit-pattern of those arguments. Return (x1 != x2) element-wise. These keywords will test the truth value of the entire array (not element-by-element as you might expect). x2[. out]) logical_or(x1. out]) arctanh(x[. Shift the bits of an integer to the left. out]) Compute the truth value of x1 AND x2 element-wise. x2[. 2. out]) Compute the bit-wise AND of two arrays element-wise. element-wise. out]) rad2deg(x[.8. Return the truth value of (x1 < x2) element-wise.6 – continued from previous page Given the “legs” of a right triangle. Inverse hyperbolic sine element-wise. bitwise_and(x1. Inverse hyperbolic tangent element-wise. logical_and(x1. Hyperbolic sine. out]) not_equal(x1. x2[. Convert angles from radians to degrees. x2[. Compute the truth value of x1 XOR x2. Compute the truth value of x1 OR x2 element-wise. x2[. out]) Return the truth value of (x1 > x2) element-wise. x2[. element-wise. Compute the bit-wise OR of two arrays element-wise. Warning: The bit-wise operators & and | are the proper way to perform element-by-element array comparisons.NumPy Reference. Compute hyperbolic tangent element-wise. x2[. 2. x2[. Use the bitwise operators & and | instead. Universal functions (ufunc) .4 Comparison functions greater(x1. x2[. Release 1.

isreal(x) iscomplex(x) isfinite(x[. where True if input element is real. out]) Element-wise minimum of array elements. The description details only a single operation.8. out]) frexp(x[.5 Floating functions Recall that all of these functions work element-by-element over an array. Change the sign of x1 to that of x2. x2[. Test element-wise for finiteness (not infinity or not Not a Number). returning an array output. Available ufuncs Returns a bool array. where True if input element is complex. out]) signbit(x[. Return the element-wise remainder of division. The reduce method of minimum also allows you to compute a total minimum over an array.1 Tip: The Python function max() will find the maximum over a one-dimensional array. looks at the (total) truth value of a > b and uses it to return either a or b (as a whole). In contrast. out2]) ldexp(x1. x2[. out]) nextafter(x1. b). out]) ceil(x[. out]) copysign(x1. Returns element-wise True where signbit is set (less than zero). out1. Return the truncated value of the input. out]) trunc(x[. b) treats the objects a and b as a whole. element-wise. 449 . out2]) fmod(x1. b). Release 1. The reduce method of the maximum ufunc is much faster. Return the next floating-point value after x1 towards x2. b) and min(a. Returns x1 * 2**x2. out]) 2. As a ufunc. A similar difference exists between minimum(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. element-wise. Also. out]) isnan(x[. but it will do so using a slower sequence interface. b) is different than that of max(a. x2[.7.NumPy Reference. out1. 2. maximum(a. element-wise. Return the ceiling of the input. out]) modf(x[. Decompose the elements of x into mantissa and twos exponent. fmax(x1. x2[. element-wise. minimum(x1. Test element-wise for NaN and return result as a boolean array. element-wise. max(a. element-wise. Test element-wise for positive or negative infinity. x2[. Return the fractional and integral parts of an array. x2[. out]) Element-wise maximum of array elements. Returns a bool array. Return the floor of the input. Element-wise minimum of array elements. Warning: the behavior of maximum(a.7. out]) fmin(x1. x2[. out]) floor(x[. out]) isinf(x[. the max() method will not give answers you might expect for arrays with greater than one dimension. element-wise.

Release 1.1 450 Chapter 2.8.NumPy Reference. Universal functions (ufunc) .

dtype]) identity(n[.empty(shape. ‘F’}. Return a 2-D array with ones on the diagonal and zeros elsewhere. dtype=float. order]) ones_like(a[.1 Ones and zeros empty(shape[.1. order. order. optional Desired output data-type. order=’C’) Return a new array of given shape and type. Return a new array of given shape and type. 3. M. dtype. Return a new array with the same shape and type as a given array. dtype.1 Array creation routines See Also: Array creation 3. The examples assume that NumPy is imported with: >>> import numpy as np A convenient way to execute examples is the %doctest_mode mode of IPython. Return a new array of given shape and type. dtype. numpy. dtype. subok]) Return a new array of given shape and type. subok]) zeros(shape[. Parameters shape : int or tuple of int Shape of the empty array dtype : data-type. order]) empty_like(a[. filled with ones. Return the identity array. optional 451 . Return an array of ones with the same shape and type as a given array. grouped by functionality. which allows for pasting of multiline examples and preserves indentation. order : {‘C’. without initializing entries. Return an array of zeros with the same shape and type as a given array. order. k. dtype. which demonstrates basic usage of the routine. dtype]) ones(shape[. filled with zeros.CHAPTER THREE ROUTINES In this chapter routine docstrings are presented. without initializing entries. Many docstrings contain example code. order]) zeros_like(a[. dtype. subok]) eye(N[.

order=’K’. ones Return a new array setting values to one. and should be used with caution. [ 496041986. ‘F’. otherwise it will be a base-class array. ‘C’ means C-order.13182611e-314. ‘C’ otherwise. 2]) array([[ -9. dtype=None. Overrides the memory layout of the result. does not set the array values to zero.empty([2. ‘A’. ‘A’ means ‘F’ if a is Fortran contiguous. dtype=int) array([[-1073741821. Release 1.6. empty Return a new uninitialized array.0. Parameters a : array_like The shape and data-type of a define these same attributes of the returned array. ‘F’ means F-order. dtype : data-type.74499359e+001. zeros_like Return an array of zeros with shape and type of input. 3. 452 Chapter 3. then the newly created array will use the sub-class type of ‘a’. 2]. and may therefore be marginally faster. subok=True) Return a new array with the same shape and type as a given array. zeros. optional New in version 1.empty_like(a. Defaults to True. Overrides the data type of the result. Returns out : ndarray Array of uninitialized (arbitrary) data with the same shape and type as a. it requires the user to manually set all the values in the array. subok : bool.0. On the other hand. Examples >>> np.empty([2. See Also: empty_like. Routines .1 Whether to store multi-dimensional data in C (row-major) or Fortran (column-major) order in memory.69583040e-309].NumPy Reference. -1067949133]. See Also: ones_like Return an array of ones with shape and type of input. optional. 6. ones Notes empty. or ‘K’}. unlike zeros.8.6. [ 2. If True.06959433e-309]]) >>> np. ‘K’ means match the layout of a as closely as possible. optional New in version 1. order : {‘C’. 19249760]]) #random #random numpy.

. [0. It may be marginally faster than the functions that do set the array values..3].00000572e+000].6]) # a is array-like >>> np. -2.NumPy Reference. M : int. 0. 1.].eye(2. and a negative value to a lower diagonal. -2. [ 0. defaults to N. Returns I : ndarray of shape (N. to do that use zeros_like or ones_like instead..M) An array where all elements are equal to zero. 3].. 2.5. dtype : data-type.eye(3.1 zeros Return a new array setting values to zero.1. 3.17269252e-309]]) numpy..5. 0.. 0.#random [ 4. Notes This function does not initialize the returned array. #random [ 0. Parameters N : int Number of rows in the output.. 0]. a positive value refers to an upper diagonal. Release 1. 1. whose values are equal to one.]]) >>> np. M=None.]]) 3.]. See Also: identity (almost) equivalent function diag diagonal 2-D array from a 1-D array specified by the user. k=1) array([[ 0. [ 0.00000715e+000.]. k=0. [4. dtype=int) array([[1. 0. 1. Examples >>> np.empty_like(a) array([[-1073741821.48219694e-323.38791518e-305.. optional Number of columns in the output. k : int. optional Data-type of the returned array. -1073741821. except for the k-th diagonal.00000715e+000.eye(N. dtype=<type ‘float’>) Return a 2-D array with ones on the diagonal and zeros elsewhere. 4. 1]]) >>> np.. 0. Array creation routines 453 . -1073741821]]) >>> a = np.8. optional Index of the diagonal: 0 (the default) refers to the main diagonal.. Examples >>> a = ([1.[4. If None.array([[1.6.2.empty_like(a) array([[ -2.

(2. [ 0.identity(3) array([[ 1. optional The desired data-type for the array. ‘F’}. 3) or 2.).. Default is numpy. 0.. optional Data-type of the output. 1. 1. 0.. 1.]]) numpy.]]) 454 Chapter 3. 1]) >>> np. See Also: zeros.. Examples >>> np.]. 1. Release 1. order : {‘C’. 1)) array([[ 1. dtype=None) Return the identity array.g.ones((2. The identity array is a square array with ones on the main diagonal. Returns out : ndarray n x n array with its main diagonal set to one. 1. 1. and all other elements 0. Parameters shape : int or sequence of ints Shape of the new array. filled with ones. order=’C’) Return a new array of given shape and type.. Routines .int8. [ 1.int) array([1.. 1. numpy. dtype : data-type.or Fortran-contiguous (row. e.. dtype=None.. and order. 1.NumPy Reference.].1 numpy.identity(n.]. 0.. 0.]) >>> np. optional Whether to store multidimensional data in C. ones_like Examples >>> np. Defaults to float. Returns out : ndarray Array of ones with the given shape. 1.ones(shape.. e..8. dtype.float64.ones(5) array([ 1.. dtype : data-type.or columnwise) order in memory.ones((5. Parameters n : int Number of rows (and columns) in n x n output. dtype=np. [ 0.g.

. optional. subok=True) Return an array of ones with the same shape and type as a given array. ‘K’ means match the layout of a as closely as possible.ones(s) array([[ 1. See Also: zeros_like Return an array of zeros with shape and type of input. 2].arange(6) >>> x = x.ones_like(x) array([[1. Returns out : ndarray Array of ones with the same shape and type as a. [1.1. 1. Defaults to True. dtype : data-type. zeros Return a new array setting values to zero. 4. optional New in version 1. Examples >>> x = np. Overrides the data type of the result.ones_like(a. optional New in version 1. 3)) >>> x array([[0. otherwise it will be a base-class array..6. Release 1.]. or ‘K’}. order=’K’.reshape((2. ones Return a new array setting values to one. ‘A’ means ‘F’ if a is Fortran contiguous. 1.]]) numpy. [3. ‘F’ means F-order.NumPy Reference. 5]]) >>> np. [ 1. 1].8. Overrides the memory layout of the result. 1. subok : bool. ‘C’ means C-order.1 >>> s = (2.6. ‘F’. empty Return a new uninitialized array. ‘C’ otherwise. 1. Array creation routines 455 .2) >>> np. 1. Parameters a : array_like The shape and data-type of a define these same attributes of the returned array.0. empty_like Return an empty array with shape and type of input.0. 1]]) 3. dtype=None. If True. order : {‘C’. ‘A’. then the newly created array will use the sub-class type of ‘a’.

..zeros(5) array([ 0. dtype : data-type. e..]) numpy. 3) or 2.]) >>> np.]]) 456 Chapter 3. 1. dtype. [ 0. 0.int) array([0. Parameters shape : int or sequence of ints Shape of the new array.float64.. Routines .g. (2.. 1)) array([[ 0. ‘F’}. 0.. 0.1 >>> y = np.zeros((5. 0. [ 0. optional Whether to store multidimensional data in C.. empty_like Return an empty array with shape and type of input. ones Return a new array setting values to one. 0.. ones_like Return an array of ones with shape and type of input. dtype=float.int8.2) >>> np. Default is numpy. 2.zeros(s) array([[ 0.arange(3. numpy. order : {‘C’.zeros((2.]) >>> np.zeros(shape. 1.]. 0... Returns out : ndarray Array of zeros with the given shape.]]) >>> s = (2. filled with zeros..].8.). 1. Examples >>> np. 0. order=’C’) Return a new array of given shape and type. See Also: zeros_like Return an array of zeros with shape and type of input.ones_like(y) array([ 1. 0..NumPy Reference.g.or Fortran-contiguous (row. 0. empty Return a new uninitialized array. Release 1. 0]) >>> np.float) >>> y array([ 0. optional The desired data-type for the array. e. and order. dtype=np.or columnwise) order in memory. dtype=numpy.

then the newly created array will use the sub-class type of ‘a’. dtype=[(’x’. order=’K’. 5]]) >>> np.arange(6) >>> x = x. ‘K’ means match the layout of a as closely as possible. ‘F’. (’y’.zeros_like(a.1 >>> np. dtype=[(’x’. zeros Return a new array setting values to zero. 1. ’<i4’). Array creation routines 457 . ’i4’)]) # custom dtype array([(0.zeros_like(x) array([[0. Overrides the memory layout of the result. 0. optional New in version 1. subok=True) Return an array of zeros with the same shape and type as a given array. subok : bool. 2]. ’<i4’)]) numpy. 0]]) 3.1.NumPy Reference. empty_like Return an empty array with shape and type of input. 0]. empty Return a new uninitialized array. See Also: ones_like Return an array of ones with shape and type of input.6. Examples >>> x = np. 3)) >>> x array([[0. Defaults to True. Release 1.0. 4. (0. 0)]. (’y’. [0. 0). ‘C’ otherwise. or ‘K’}. ‘F’ means F-order. optional. dtype : data-type. ‘C’ means C-order. Overrides the data type of the result. Returns out : ndarray Array of zeros with the same shape and type as a.0. dtype=None.8. 0. Parameters a : array_like The shape and data-type of a define these same attributes of the returned array. [3.6.). order : {‘C’. otherwise it will be a base-class array. ones Return a new array setting values to one. ‘A’.reshape((2. optional New in version 1.zeros((2. If True. ‘A’ means ‘F’ if a is Fortran contiguous. ’i4’).

1 >>> y = np. Create a new 1-dimensional array from an iterable object. Convert the input to an array.. 0. dtype. optional If true (default). A new 1-D array initialized from raw binary or text data in a string. optional The desired data-type for the array. then the object is copied. order]) frombuffer(buffer[. count. count.]) >>> np. dtype. If order is ‘C’ (default). Release 1. etc..]) 3.. dtype. dtype]) asmatrix(data[. sep]) fromfunction(function. dtype. if obj is a nested sequence. then the returned array may be in any order (either C-. or if a copy is needed to satisfy any of the other requirements (dtype. If order is ‘F’. subok : bool. dtype]) copy(a[. If order is ‘A’. dtype=np. ndmin]) asarray(a[. This argument can only be used to ‘upcast’ the array. then the returned array will be in Fortran-contiguous order (first-index varies the fastest). ndmin : int. copy. otherwise the returned array will be forced to be a base-class array (default). dtype : data-type. dtype. order=None.NumPy Reference.astype(t) method. any object exposing the array interface.. use the . order : {‘C’. a copy will only be made if __array__ returns a copy..arange(3. If not given. or even discontiguous). then the type will be determined as the minimum type required to hold the objects in the sequence. order]) asanyarray(a[. optional 458 Chapter 3. For downcasting. count. comments.]) Create an array. dtype=None. Otherwise. Construct an array from data in a text or binary file. copy=True. **kwargs) fromiter(iterable. order]) ascontiguousarray(a[. order. Construct an array by executing a function over each coordinate. Interpret a buffer as a 1-dimensional array. optional Specify the order of the array. 2. Convert the input to an ndarray. ‘A’}. or any (nested) sequence. Return an array copy of the given object. dtype. but pass ndarray subclasses through. numpy. then sub-classes will be passed-through.array(object.. Fortran-contiguous. ndmin=0) Create an array.2 From existing data array(object[. Interpret the input as a matrix. then the array will be in Ccontiguous order (last-index varies the fastest).float) >>> y array([ 0. . delimiter. optional If True. copy : bool. subok. shape. Return a contiguous array in memory (C order).8. 1. an object whose __array__ method returns an array. dtype. Parameters object : array_like An array. count]) fromstring(string[. dtype[.). order. sep]) loadtxt(fname[.1. subok=False. Routines . 0.zeros_like(y) array([ 0. Load data from a text file. offset]) fromfile(file[. ‘F’.

2).array(np.0]) array([ 1.4)]. 3 4’).array([1. See Also: empty. 3]) Creating an array from sub-classes: >>> np. 4]]) >>> np. 2]. tuples of tuples.NumPy Reference. 3]]) Type provided: >>> np. 2]. order=None) Convert the input to an array. dtype=complex) array([ 1. Ones will be pre-pended to the shape as needed to meet this requirement. Parameters a : array_like Input data.1.1 Specifies the minimum number of dimensions that the resulting array should have. empty_like.array([1. [3. 3.j. 3]. [3. 3. 3].8. 2.(’b’.j]) Data-type consisting of more than one element: >>> x = np.j.]) More than one dimension: >>> np. 4]]) array([[1.asarray(a.array([[1.dtype=[(’a’. 3 4’)) array([[1. 4]]) Minimum dimensions 2: >>> np.array([(1. 2. ones. subok=True) matrix([[1. zeros_like. ndmin=2) array([[1.(3. 4]]) numpy..mat(’1 2. 3]) array([1. 3. zeros. Array creation routines 459 . [3.’<i4’)]) >>> x[’a’] array([1. dtype=None. This includes lists. [3. 3]) Upcasting: >>> np.+0.array(np.’<i4’). tuples.. 2. 3. tuples of lists and ndarrays. 2.mat(’1 2. lists of tuples.+0. Returns out : ndarray An array object satisfying the specified requirements. 2]. 2. 2. fill Examples >>> np. 2.array([1. ones_like. in any form that can be converted to an array. 2. Release 1.+0. 2].array([1.

See Also: asanyarray Similar function which passes through subclasses.NumPy Reference.array([1.float32) >>> np.8. Defaults to ‘C’. optional Whether to use row-major (‘C’) or column-major (‘F’ for FORTRAN) memory representation. fromiter Create an array from an iterator. Returns out : ndarray Array interpretation of a.asarray(a. order : {‘C’. ‘F’}. a base class ndarray is returned. Routines . dtype=np. the data-type is inferred from the input data. array is copied only if dtype does not match: >>> a = np. fromfunction Construct an array by executing a function on grid positions.1 dtype : data-type. ascontiguousarray Convert input to a contiguous array.asarray(a.asarray(a) is a True If dtype is set. If a is a subclass of ndarray. Examples Convert a list into an array: >>> a = [1. asfortranarray Convert input to an ndarray with column-major memory order. 2] >>> np.asarray(a) array([1.array([1. dtype=np. Release 1.float32) is a True >>> np. 2]) >>> np. No copy is performed if the input is already an ndarray. optional By default. ndarray subclasses are not passed through: 460 Chapter 3. 2]. asarray_chkfinite Similar function which checks input for NaNs and Infs. asfarray Convert input to a floating point ndarray. 2]) Existing arrays are not copied: >>> a = np. dtype=np.float64) is a False Contrary to asanyarray.

matrix. but pass ndarray subclasses through.asanyarray(a) is a True numpy. tuples of tuples. tuples. np. lists.8.matrix([[1. Array creation routines 461 . fromiter Create an array from an iterator. 2]]) >>> np. optional Whether to use row-major (‘C’) or column-major (‘F’) memory representation. dtype=None. ‘F’}. Release 1. and ndarrays. asfortranarray Convert input to an ndarray with column-major memory order. 2] >>> np. 2]) 3. ascontiguousarray Convert input to a contiguous array. Returns out : ndarray or an ndarray subclass Array interpretation of a. it is returned as-is and no copy is performed.asanyarray(a) array([1. If a is an ndarray or a subclass of ndarray. Examples Convert a list into an array: >>> a = [1. order=None) Convert the input to an ndarray.1 >>> issubclass(np. lists of tuples. fromfunction Construct an array by executing a function on grid positions. This includes scalars. the data-type is inferred from the input data. asarray_chkfinite Similar function which checks input for NaNs and Infs. optional By default. asfarray Convert input to a floating point ndarray.asarray(a) is a False >>> np. dtype : data-type.asanyarray(a. in any form that can be converted to an array. Parameters a : array_like Input data.NumPy Reference. order : {‘C’. Defaults to ‘C’.ndarray) True >>> a = np.1. tuples of lists. See Also: asarray Similar function which always returns ndarrays.

1.matrix([1. dtype=None) Return a contiguous array in memory (C order). Parameters a : array_like Input array.. 5. 2]) >>> np.]].NumPy Reference.flags[’C_CONTIGUOUS’] True numpy.asmatrix(data. 2. dtype=np. asmatrix does not make a copy if the input is already a matrix or an ndarray. copy=False). [ 3.3) >>> np. dtype=None) Interpret the input as a matrix. optional Data-type of returned array. with type dtype if specified. 4]]) 462 Chapter 3.1 Instances of ndarray subclasses are passed through as-is: >>> a = np.array([[1. 4. Unlike matrix. [3.asanyarray(a) is a True numpy. Examples >>> x = np.. Returns mat : matrix data interpreted as a matrix.ascontiguousarray(x. require Return an ndarray that satisfies requirements. Release 1.. Examples >>> x = np. See Also: asfortranarray Convert input to an ndarray with column-major memory order.arange(6).. Returns out : ndarray Contiguous array of same shape and content as a.flags Information about the memory layout of the array. dtype : str or dtype object.reshape(2. 2]. Routines . dtype=float32) >>> x.]. Equivalent to matrix(data.float32) array([[ 0.ascontiguousarray(a. ndarray.8. Parameters data : array_like Input data.

order=’K’) Return an array copy of the given object. order : {‘C’. dtype=float. offset=0) Interpret a buffer as a 1-dimensional array.0] = 5 >>> m matrix([[5. Parameters a : array_like Input data. ‘F’. when we modify x. count : int. optional Controls the memory layout of the copy. 4]]) numpy.NumPy Reference. ‘F’ means F-order. optional 3.copy(a. ‘C’ otherwise. 2.copy(x) Note that. ‘K’}.1 >>> m = np.copy are very similar. Parameters buffer : buffer_like An object that exposes the buffer interface. copy=True) Examples Create an array x.array([1. y changes. Array creation routines 463 . 3]) >>> y = x >>> z = np.array(a. ‘A’. 2]. but have different default values for their order= arguments. with a reference y and a copy z: >>> x = np. (Note that this function and :meth:ndarray.asmatrix(x) >>> x[0. ‘C’ means C-order. default: float.frombuffer(buffer. optional Data-type of the returned array.1.8. Release 1. Notes This is equivalent to >>> np. ‘K’ means match the layout of a as closely as possible. [3. ‘A’ means ‘F’ if a is Fortran contiguous. dtype : data-type.) Returns arr : ndarray Array interpretation of a. count=-1. but not z: >>> x[0] = 10 >>> x[0] == y[0] True >>> x[0] == z[0] False numpy.

count=-1. no byte-order or data-type information is saved. ’r’. -1 means all data in the buffer. offset : int.npy format using save and load instead. A highly efficient way of reading binary data with a known data-type. e. count=5. ndarray.frombuffer(s. sep : str Separator between items if file is a text file. Notes If the buffer has data that is not in machine byte-order. optional Start reading the buffer from this offset. 464 Chapter 3. as well as parsing simply formatted text files. Routines . the complete file).1 Number of items to read.NumPy Reference. dtype=float.tofile loadtxt More flexible way of loading data from a text file.g. default: 0. For binary files. save. Empty (“”) separator means the file should be treated as binary. ’d’]. Release 1.fromfile(file. dtype=’S1’. A separator consisting only of spaces must match at least one whitespace. Data written using the tofile method can be read using this function.newbyteorder(’>’) >>> np. In particular. but will be interpreted correctly. sep=’‘) Construct an array from data in a text or binary file. this should be specified as part of the data-type. dtype : data-type Data type of the returned array.dtype(int) >>> dt = dt.e. Examples >>> s = ’hello world’ >>> np. count : int Number of items to read.frombuffer(buf. See Also: load. Notes Do not rely on the combination of tofile and fromfile for data storage. Spaces (” ”) in the separator match zero or more whitespace characters. as the binary files generated are are not platform independent.. it is used to determine the size and byte-order of the items in the file. offset=6) array([’w’. -1 means all items (i. ’o’. dtype=dt) The data of the resulting array will not be byteswapped.: >>> dt = np.8. dtype=’|S1’) numpy. Data can be stored in the platform independent . ’l’. Parameters file : file or str Open file object or filename.

load(fname + ’.tofile(fname) Read the raw data from disk: >>> np. **kwargs) Construct an array by executing a function over each coordinate. shape. where N is the rank of shape.tmpnam() >>> x. (1. ’<f8’)]) Save the raw data to disk: >>> import os >>> fname = os. 0). For example.. [(’min’.1 Examples Construct an ndarray: >>> dt = np. z) at coordinate (x. dtype=dt) >>> x[’time’][’min’] = 10. dtype=[(’time’.25)]. 0). [(’min’. which also determines the shape of the coordinate arrays passed to function.) tuple of ints Shape of the output array. Returns fromfunction : any The result of the call to function is passed back directly.fromfile(fname.zeros((1. dtype : data-type. 98. If function returns a scalar value. int)]).save(fname. ’<i4’). 98. dtype=dt) array([((10. y.npy’) array([((10. (’temp’. optional Data-type of the coordinate arrays passed to function.8. ’<i4’). dtype is float. ’<i4’)]). (1. 98.25)]. Array creation routines 465 . [(’min’. . (’temp’. meshgrid 3. Release 1.25)]. 0). ’<f8’)]) numpy. x[’temp’] = 98. if shape were (2. float)]) >>> x = np. (’sec’. shape : (N. Therefore the shape of fromfunction is completely determined by function. By default. ’<i4’). [(’min’. (0. 2). z). (’temp’.fromfunction(function.1. (’sec’. ’<i4’)]).. y. 1). Parameters function : callable The function is called with N parameters. The resulting array therefore has a value fn(x. dtype=[(’time’. the shape of fromfunction would match the shape parameter. 0). dtype=[(’time’. (’sec’.NumPy Reference. (’sec’. ’<i4’)]). Each parameter represents the coordinates of the array varying along a specific axis. 0). (’temp’.25 >>> x array([((10.dtype([(’time’. int). ’<f8’)]) The recommended way to store and load data: >>> np. then the parameters in turn be (0. 1). See Also: indices.). x) >>> np.

1.1 Notes Keywords other than dtype are passed to function. 2. False]. 4. Parameters string : str A string containing the data. dtype=float. 16. It allows fromiter to pre-allocate the output array.]) numpy.float) array([ 0. optional 466 Chapter 3.fromfunction(lambda i. False. Routines . [False. The default is -1. Release 1. 3). j: i + j. True. optional The data type of the array. For binary input data. np.fromiter(iterable.fromfunction(lambda i. dtype=int) array([[0.. False. optional The number of items to read from iterable.. (3. dtype. Returns out : ndarray The output array.. count=-1. dtype=bool) >>> np. Examples >>> iterable = (x*x for x in range(5)) >>> np.fromiter(iterable. True]]. 1. False]. [2. count=-1) Create a new 1-dimensional array from an iterable object.8. 3. [1. j: i == j. Parameters iterable : iterable object An iterable object providing data for the array.. the data must be in exactly this format.fromstring(string. Examples >>> np. dtype : data-type The data-type of the returned array. 9. dtype : data-type. sep=’‘) A new 1-D array initialized from raw binary or text data in a string. dtype=int) array([[ True. (3. 3). which means all data is read. instead of resizing it on demand. Notes Specify count to improve performance.NumPy Reference. count : int. 2]. [False. default: float. count : int. 3]. 4]]) numpy.

the data will be interpreted as binary data.NumPy Reference. converters=None. as ASCII text with decimal numbers. 2. sep=’ ’) array([1. dtype=int. the empty string. optional The string used to separate values. Array creation routines 467 . or generator to read.fromstring(’1 2’. dtype=<type ‘float’>. If the filename extension is . optional 3. the count will be determined from the length of the data. the number of columns used must match the number of fields in the datatype.8.’) array([1. If this is negative (the default). sep : str.uint8. 2]. Release 1.fromstring(’\x01\x02\x03\x04\x05’. equivalently. Parameters fname : file or str File. Also in this latter case. optional The character used to indicate the start of a comment. filename. Note that generators should return byte strings for Python 3k. See Also: frombuffer. If this is a record data-type. dtype=np.uint8) array([1. count=3) array([1. optional If not provided or.fromstring(’\x01\x02’. 2]) >>> np. otherwise. dtype=uint8) numpy. sep=’. optional Data-type of the resulting array. By default. fromiter Examples >>> np. delimiter : str. unpack=False. dtype=int. comments=’#’. fromfile. default: float. this is any whitespace. extra whitespace between elements is also ignored. the file is first decompressed.gz or . usecols=None.fromstring(’1. skiprows=0. converters : dict.1. 3]. delimiter=None. Raises ValueError If the string is not the correct size to satisfy the requested dtype and count. comments : str. 2]) >>> np. dtype=np. and each row will be interpreted as an element of the array.1 Read this number of dtype elements from the data. Returns arr : ndarray The constructed array.bz2. this argument is interpreted as the string separating numbers in the data. the resulting array will be 1-dimensional.loadtxt(fname. default: ‘#’. In this case. dtype : data-type. 2’. dtype=uint8) >>> np. Each row in the text file must have the same number of values. ndmin=0) Load data from a text file.

the returned array is transposed. optional If True. so that arguments may be unpacked using x. fromstring.4.io. ’weight’). ’<i4’). E. ’f4’)}) array([(’M’.].loadtxt(d. When used with a record data-type. dtype=[(’gender’.). Converters can also be used to provide a default value for missing data (but see also genfromtxt): converters = {3: lambda s: float(s.8.g. See Also: load.. usecols : sequence. The default. if column 0 is a date string: converters = {0: datestr2num}..6. Routines . 5th and 6th columns. Default is False. ’age’.loadtxt(c) array([[ 0. skiprows : int. None. fromregex genfromtxt Load data with missing values handled as specified. lines with missing values..1 A dictionary mapping column number to a function that will convert that column to a float. scipy.5) will extract the 2nd. default: 0. optional The returned array will have at least ndmin dimensions. 35. dtype={’names’: (’gender’. Examples >>> from StringIO import StringIO >>> c = StringIO("0 1\n2 3") >>> np..g. ndmin : int. ’i4’. optional Skip the first skiprows lines.loadmat reads MATLAB data files Notes This function aims to be a fast reader for simply formatted files... For example.0). New in version 1. 1. The genfromtxt function provides more sophisticated handling of. Otherwise mono-dimensional axes will be squeezed. optional Which columns to read. (’F’. 58.]]) # StringIO behaves like a file object >>> d = StringIO("M 21 72\nF 35 58") >>> np. results in all columns being read.. usecols = (1. Release 1. arrays are returned for each field. 72. 1 or 2. (’weight’. z = loadtxt(. e. Default: None.strip() or 0)}.0. [ 2. unpack : bool. Legal values: 0 (default). y. 21.. ’|S1’). Returns out : ndarray Data read from the text file. . with 0 being the first. 3. ’<f4’)]) 468 Chapter 3. ’formats’: (’S1’.0)].NumPy Reference. (’age’.

col3’) >>> print r[0] (456. create a record array from a (flat) list of arrays create a recarray from a list of records in text form create a (read-only) record array from binary data contained in Create an array from binary file data numpy. y = np. shape=None. dtype. names=None.core.1..8. delimiter=’.. ’dbe’. dtype=None.records.2.1.’12’]) >>> x3=np. core.records..’dd’.NumPy Reference. 4]) numpy. names=None.array([’a’. byteorder=None) create a record array from a (flat) list of arrays >>> x1=np. This method is intended for creating smaller record arrays.. . copy=True) Construct a record array from a wide-variety of objects. dtype.3.. offset=0.fromfile(fd[. 2).records. unpack=True) >>> x array([ 1. byteorder=None) create a recarray from a list of records in text form The data in the same field can be heterogeneous. formats=None.x3]. >>> r=np. strides=None. 3. Release 1. If used to create large array without formats defined r=fromrecords([(2.records.3.1 >>> c = StringIO("1. dtype=None. byteorder=None...2\n3. .. shape=None. 1.records. they will be promoted to the highest data type.core.records. titles=None.array([1. Use list of tuples rather than list of lists for faster processing.3 Creating record arrays (numpy.core.col2. .array([1. numpy. . usecols=(0.2).1..array(obj. Array creation routines 469 .’xyz’.4]) >>> r = np.. dtype.]) core. then this will auto-detect formats.0.3.2.]) core.2) >>> r.c’) >>> print r[1] (2. aligned=False.3)].]) Construct a record array from a wide-variety of objects. titles=None.array(obj[. names=None.rec) Note: numpy.1.’abc’)]*100000) it can be slow.records.0..b. shape. shape. dtype.a array([1. formats=None.0) >>> x1[1]=34 >>> r.’. If formats is None.fromarrays([x1.rec is the preferred alias for numpy.fromrecords(recList[.records.4]) >>> x2=np.loadtxt(c. dtype=None. aligned=False.core. .’de’.(2. dtype. 3. ’dd’. titles=None.fromrecords(recList.core.x2.4") >>> x. names=’col1. shape=None. aligned=False.fromstring(datastring[.records.]) 3.]) >>> y array([ 2..fromarrays(arrayList[.]) core..’dbe’. 2. . 2.]) core.records. 4. formats=None.fromarrays(arrayList.records.core...fromrecords([(456.names=’a.1.col1 3.

dtype=None. order=None) Create a chararray.records.3)] numpy.defchararray. formats=’f8. unicode=None. .dumps(r)) [(456.]) core. itemsize.i4. names=None.fromstring(datastring. >>> from tempfile import TemporaryFile >>> a = np. byteorder=’<’) >>> print r[5] (0. titles=None. offset=0.i4. 1. byteorder=None) create a (read-only) record array from binary data contained in a string numpy.core.8.1 array([456.char is the preferred alias for numpy. 10.core.2) (2. Release 1. itemsize. formats=None. . shape=None.core.newbyteorder(’<’) >>> a.core.defchararray..shape (10. offset=0.defchararray.char for fast vectorized string operations instead.) 3.records.5. titles=None.records.asarray(obj[. names=None. shape=10.]) Create a chararray. Convert the input to a chararray.array(obj[. aligned=False..comparison operators automatically remove whitespace from the end when comparing values 470 Chapter 3.array(obj. Versus a regular Numpy array of type str or unicode. copy=True. ’de’]. byteorder=None) Create an array from binary file data If file is a string then that file is opened.10.NumPy Reference. else it is assumed to be a file object. ... Note: This class is provided for numarray backward-compatibility.a5’. copying the data only if necessary. ’de’.col2 chararray([’dbe’. this class adds the following functionality: 1.dtype=’f8. shape=None.empty(10.1. 1. itemsize=None.char) Note: numpy..’abcde’) >>> >>> fd=TemporaryFile() >>> a = a.tofile(fd) >>> >>> fd.loads(pickle. ’dbe’. ’abcde’) >>> r.defchararray.fromfile(fd.core. numpy. New code (not concerned with numarray compatibility) should use arrays of type string_ or unicode_ and use the free functions in numpy. formats=None.values automatically have whitespace removed from the end when indexed 2.fromfile(fd.4 Creating character arrays (numpy.5.. aligned=False. dtype=None. Routines . core. 2]) >>> r.a5’) >>> a[5] = (0.seek(0) >>> r=np. dtype=’|S3’) >>> import pickle >>> print pickle.

then the obj string will be chunked into itemsize pieces. copying the data only if necessary. Array creation routines 471 . Otherwise. • an ndarray of type str or unicode • a Python str or unicode object. If itemsize is provided and obj is of type str or unicode. If itemsize is None. and obj is an object array or a Python list. the itemsize will be automatically determined.g. then the array will be in Ccontiguous order (last-index varies the fastest). then the unicode setting of the output array will be automatically determined. if obj is a nested sequence. If order is ‘F’. when false only 8-bit characters. Release 1.g. unicode=None. str. %) Parameters obj : array of str or unicode-like itemsize : int.vectorized string operations are provided as methods (e. unicode : bool.). optional Specify the order of the array. unicode : bool.asarray(obj. or if a copy is needed to satisfy any of the other requirements (itemsize. etc. Fortran-contiguous.vectorized string operations are provided as methods (e. then the object is copied. itemsize=None. then the returned array may be in any order (either C-. If itemsize is provided and obj is of type str or unicode. *. and obj is an object array or a Python list. the itemsize will be automatically determined. If unicode is None and obj is one of the following: • a chararray. optional 3. str.endswith) and infix operators (e. +. this class adds the following functionality: 1. If order is ‘A’. numpy.comparison operators automatically remove whitespace from the end when comparing values 3. *.values automatically have whitespace removed from the end when indexed 2. optional itemsize is the number of characters per scalar in the resulting array.NumPy Reference.g. optional If true (default).defchararray. Versus a regular Numpy array of type str or unicode. copy : bool. +. optional When true. If itemsize is None.8. order=None) Convert the input to a chararray. ‘A’}. then the returned array will be in Fortran-contiguous order (first-index varies the fastest). optional itemsize is the number of characters per scalar in the resulting array. the resulting chararray can contain Unicode characters.endswith) and infix operators (e. a copy will only be made if __array__ returns a copy. %) Parameters obj : array of str or unicode-like itemsize : int. ‘F’. order.g. order : {‘C’.1. or even discontiguous).core. unicode. If order is ‘C’ (default).1 3. then the obj string will be chunked into itemsize pieces.

stop[. The interval does not include this value. stop[. out[i+1] . then the unicode setting of the output array will be automatically determined. • an ndarray of type str or ‘unicode‘ • a Python str or unicode object. nd_grid instance which returns a dense multi-dimensional “meshgrid”. but returns an ndarray rather than a list.8. num. dtype=None) Return evenly spaced values within a given interval. If step is specified. then the returned array will be in Fortran-contiguous order (first-index varies the fastest).NumPy Reference. the results will often not be consistent. Release 1. step. when false only 8-bit characters. except in some cases where step is not an integer and floating point round-off affects the length of out. stop) (in other words.][. If order is ‘F’. The default start value is 0. Parameters start : number. Values are generated within the half-open interval [start. endpoint. dtype : dtype The type of the output array. optional Spacing between values. 3. the resulting chararray can contain Unicode characters. If order is ‘C’ (default).1. Returns arange : ndarray 472 Chapter 3. this is the distance between two adjacent values. Return numbers spaced evenly on a log scale. The interval includes this value.] stop[. If unicode is None and obj is one of the following: • a chararray. num. **kwargs) mgrid ogrid Return evenly spaced values within a given interval. the interval including start but excluding stop). optional Start of interval. For any output out. Return evenly spaced numbers over a specified interval. then the array will be in Ccontiguous order (last-index varies the fastest). numpy. optional Specify the order of the array.arange([start ]. endpoint.5 Numerical ranges arange([start. The default step size is 1.out[i].1. step : number. Return coordinate matrices from two or more coordinate vectors. stop : number End of interval. If dtype is not given. infer the data type from the other input arguments. ‘F’}. nd_grid instance which returns an open multi-dimensional “meshgrid”. start must also be given. When using a non-integer step. It is better to use linspace for these cases. For integer arguments the function is equivalent to the Python built-in range function. stop[. Routines . retstep]) logspace(start. such as 0.1 When true. dtype]) linspace(start. order : {‘C’. step ]. base]) meshgrid(*xi.

5]) numpy. 1. optional Number of samples to generate. retstep : bool.0) array([ 0. stop is the last sample. mgrid Grid-shaped arrays of evenly spaced numbers in N-dimensions. Otherwise.arange(3.linspace(start. See Also: linspace Evenly spaced numbers with careful handling of endpoints.arange(3. For floating point arguments. Because of floating point overflow. 3. Returns num evenly spaced samples.7. where step is the spacing between samples. this rule may result in the last element of out being greater than stop. unless endpoint is set to False.1. Note that the step size changes when endpoint is False. Release 1. stop ]. Parameters start : scalar The starting value of the sequence. retstep=False) Return evenly spaced numbers over a specified interval. 4. 2. Array creation routines 473 . return (samples.arange(3. num : int.2) array([3. endpoint : bool.NumPy Reference.1 Array of evenly spaced values. Returns samples : ndarray There are num equally spaced samples in the closed interval [start. it is not included. The endpoint of the interval can optionally be excluded. step). Default is 50. the sequence consists of all but the last of num + 1 evenly spaced samples. 5. endpoint=True. calculated over the interval [start.]) >>> np. num=50. stop) (depending on whether endpoint is True or False).. optional If True. the length of the result is ceil((stop start)/step). stop] or the half-open interval [start. Examples >>> np. stop. In that case. Default is True.7) array([3.8.arange(3) array([0. so that stop is excluded. stop : scalar The end value of the sequence. ogrid Arrays of evenly spaced numbers in N-dimensions. 6]) >>> np. optional If True.. 2]) >>> np. 1.

75.5 .plot(x2. 2.ylim([-0. 474 Chapter 3.0.4 0 2 4 6 8 10 numpy. num=5. 2. Release 1.0.25. ’o’) [<matplotlib. N. ]). 0. num=5. ’o’) [<matplotlib.plot(x1.lines.zeros(N) >>> x1 = np.4 0.2 0. but uses a step size (instead of the number of samples). 1]) (-0.0. 3. y + 0.8 0. . 2.5.linspace(0. 10.lines.NumPy Reference. 2. See Also: arange Similar to linspace.25) Graphical illustration: >>> import matplotlib. endpoint=False) >>> plt.0 0. N. Routines .linspace(0. .5. 3. 2.0) Return numbers spaced evenly on a log scale.linspace(2.2 0.75.>] >>> plt. 2. . 3.pyplot as plt >>> N = 8 >>> y = np..show() 1.>] >>> plt. y.0. num=5) array([ 2.1 step : float (only if retstep is True) Size of spacing between samples. stop. logspace Samples uniformly distributed in log space. endpoint=True.logspace(start.0.linspace(2.. ]) >>> np.8]) >>> np. 3.. 10. endpoint=True) >>> x2 = np. 1) >>> plt.linspace(2. 3. num=50.. 2.4.6.5 .Line2D object at 0x.25.5. 2. Examples >>> np.2.6 0.8. 2.0. retstep=True) (array([ 2. 2. endpoint=False) array([ 2.0 0.Line2D object at 0x. base=10.

with the step size specified instead of the number of samples. the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).0.logspace(2. >>> power(base. 215.0. endpoint=False) array([ 100. Examples >>> np.0. num=4.0. y) .linspace(start. Otherwise.0.. stop. stop is the last sample. endpoint : boolean.15888336. >>> np. instead of log space. equally spaced on a log scale. base : float. See Also: arange Similar to linspace. but with the samples uniformly distributed in linear space.8. optional Number of samples to generate. optional The base of the log space.0.logspace(2.. 8. ]) ]) Graphical illustration: 3. . num + 1 values are spaced over the interval in log-space.827941 . 177. the endpoint may or may not be included. it is not included. In that case.1 In linear space. num=num. 316. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Parameters start : float base ** start is the starting value of the sequence. 6. Release 1. endpoint=endpoint) . Notes Logspace is equivalent to the code >>> y = np. .logspace(2. num=4. linspace Similar to logspace.0396842 . optional If true. Default is 50. when used with a float endpoint.NumPy Reference. Array creation routines 475 . unless endpoint is False. of which all but the last (a sequence of length num) are returned.34960421.. num : integer.34132519]) >>> np. 464.22776602.. base=2. Default is 10.1. 5.0. 1000. Returns samples : ndarray num samples.443469 . 3. 3. Default is True. . 562. stop : float base ** stop is the final value of the sequence. Note that. num=4) array([ 100.0) array([ 4. 3.

1) >>> plt. **kwargs) Return coordinate matrices from two or more coordinate vectors. copy=False will likely return non-contiguous arrays. endpoint=False) >>> y = np. ’o’) [<matplotlib. If you need to write to the arrays.. X2. given onedimensional coordinate arrays x1. more than one element of a broadcast array may refer to a single memory location.5.>] >>> plt.lines.1.8 0.NumPy Reference. y + 0. ’o’) [<matplotlib. Furthermore. optional If False.8..plot(x2..pyplot as plt >>> N = 10 >>> x1 = np. XN : ndarray 476 Chapter 3.. 1]) (-0. x2.meshgrid(*xi. x2. Routines . copy : bool... N. Default is True. y. N.lines.2 0.5.logspace(0.... optional If True a sparse grid is returned in order to conserve memory. 1.plot(x1. xn.. Returns X1.. default) or matrix (‘ij’) indexing of output.4 1 2 3 4 5 6 7 8 9 10 numpy..show() 1.6 0. sparse : bool. optional Cartesian (‘xy’. Default is False.1 >>> import matplotlib.Line2D object at 0x.>] >>> plt. Release 1. Please note that sparse=False.2 0. Parameters x1. indexing : {‘xy’. Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids. make copies first.zeros(N) >>> plt..5.. 1.1. ‘ij’}.0 0. a view into the original arrays are returned in order to conserve memory.logspace(0. xn : array_like 1-D arrays representing the coordinates of a grid... endpoint=True) >>> x2 = np. See Notes for more details.Line2D object at 0x.4 0.0 0.ylim([-0.

ny) >>> xv. yv[i.z) 3. In the 3-D case with inputs of length M. Array creation routines 477 .1) np. M) for ‘xy’ indexing and (M. 0.Nn) shaped arrays if indexing=’xy’ with the elements of xi repeated to fill the matrix along the first dimension for x1. >>> >>> >>> >>> >>> x = y = xx.8. N3.j]. [ 1. 1. [ 1.linspace(0.5. N and P.. ]]) >>> yv array([[ 0.... The difference is illustrated by the following code snippet: xv. Notes This function supports both indexing conventions through the indexing keyword argument. 0. P) for ‘xy’ indexing and (M.. 5. . 1. sparse=False.i]. ‘xn’ with lengths Ni=len(xi) . 0. 5.arange(-5.Nn) shaped arrays if indexing=’ij’ or (N2. y.. 0. In the 2-D case with inputs of length M and N. 1. sparse=False....5. the indexing and sparse keywords have no effect..].. sparse=True) >>> xv array([[ 0.y..contourf(x. [ 0.1 For vectors x1. 0. Examples >>> nx.].NumPy Reference. M. 2) >>> x = np.]]) >>> xv. ]. yv = meshgrid(x. y) >>> xv array([[ 0. yv = meshgrid(x. ]]) >>> yv array([[ 0.5..1. y. ny = (3. Release 1. Giving the string ‘ij’ returns a meshgrid with matrix indexing.]]) # make sparse output arrays meshgrid is very useful to evaluate functions on a grid.ogrid Construct an open multi-dimensional “meshgrid” using indexing notation. yv = meshgrid(x. N3.arange(-5. outputs are of shape (N. y.i] In the 1-D and 0-D case. return (N1.1) yy = meshgrid(x. N2. nx) >>> y = np. the outputs are of shape (N. 1. 0. . indexing=’ij’) for i in range(nx): for j in range(ny): # treat xv[i. N) for ‘ij’ indexing.sin(xx**2 + yy**2) / (xx**2 + yy**2) plt. 1. sparse=True) np. the second for x2 and so on. 1..linspace(0. P) for ‘ij’ indexing. 0. yv[j. N. yv = meshgrid(x. index_tricks. z = h = np. See Also: index_tricks. indexing=’xy’) for i in range(nx): for j in range(ny): # treat xv[j. x2.mgrid Construct a multi-dimensional “meshgrid” using indexing notation. y. 1. N1.j] xv. . while ‘xy’ returns a meshgrid with Cartesian indexing.

3. 0. [0.e. Returns mesh-grid ndarrays all of the same dimensions See Also: numpy.NumPy Reference. 3.g.index_tricks. -0. then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values. 4].8.ogrid = <numpy. 3. 2. 3]. not fleshed out) meshgrid when indexed.lib.lib. Routines .lib. If the step length is not a complex number. 0.mgrid[-1:1:5j] array([-1. then the stop is not inclusive.index_tricks. 1. 0]. ]) numpy. 2. so that each returned argument has the same shape.lib. so that only one dimension of each returned array is greater than 1. [0.g. The dimensions and number of the output arrays are equal to the number of indexing dimensions.index_tricks.5. Returns mesh-grid ndarrays with only one dimension 6= 1 See Also: np.nd_grid which returns an dense (or fleshed out) mesh-grid when indexed. where the stop value is inclusive.index_tricks.mgrid = <numpy.nd_grid which returns an open (i.0:5] array([[[0. 4]. 2]. 1.nd_grid object at 0x25df2d0> nd_grid instance which returns an open multi-dimensional “meshgrid”. 1. 2. where the stop value is inclusive. 2. 2. then the integer part of its magnitude is interpreted as specifying the number of points to create between the start and stop values. 5j).5. 3. [[0. 4]. 0.lib. 2. An instance of numpy.nd_grid object at 0x25df1d0> nd_grid instance which returns a dense multi-dimensional “meshgrid”. [0.lib. 1. 3. if the step length is a complex number (e. However.index_tricks. 3. [0. [1. .nd_grid class of ogrid and mgrid objects ogrid like mgrid but returns open (not fleshed out) mesh grids r_ array concatenator Examples >>> np. 4]]]) >>> np. 2. 3. 0. However. Release 1. [2. 4]. [4. 3. An instance of numpy. 0. 1.index_tricks. 4.nd_grid class of ogrid and mgrid objects 478 Chapter 3. 2. The dimension and number of the output arrays are equal to the number of indexing dimensions. 1. 4. . then the stop is not inclusive. 1. 5j). 1.mgrid[0:5. 4. if the step length is a complex number (e. 1. 4]]. [3. 1].1 numpy. If the step length is not a complex number.

3. numpy. [4]]). Create a two-dimensional array with the flattened input as a diagonal. k : int. 0. optional Diagonal in question. 0. whether it returns a copy or a view depends on what version of numpy you are using. [1].1 mgrid like ogrid but returns dense (or fleshed out) mesh grids r_ array concatenator Examples >>> from numpy import ogrid >>> ogrid[-1:1:5j] array([-1.diagonal if you use this function to extract a diagonal and wish to write to the resulting array.5. [2].8. k]) triu(m[.1. return a copy of its k-th diagonal. 3. Use k>0 for diagonals above the main diagonal. dtype]) tril(m[. k]) vander(x[.NumPy Reference. The default is 0. See Also: diagonal Return specified diagonals. M.5. and k<0 for diagonals below the main diagonal.diag(v. diagflat Create a 2-D array with the flattened input as a diagonal. Release 1.1. 2. k]) tri(N[. array([[0. . k=0) Extract a diagonal or construct a diagonal array.0:5] [array([[0]. Lower triangle of an array. . An array with ones at and below the given diagonal and zeros elsewhere. N]) Extract a diagonal or construct a diagonal array. 1. [3]. Generate a Van der Monde matrix. Upper triangle of an array. 4]])] 3. Array creation routines 479 . k]) diagflat(v[. If v is a 1-D array. Returns out : ndarray The extracted diagonal or constructed diagonal array.6 Building matrices diag(v[. -0. Parameters v : array_like If v is a 2-D array. 1. See the more detailed documentation for numpy. ]) >>> ogrid[0:5. return a 2-D array with v on the k-th diagonal. k.

0.diagflat(v. 1.arange(9).diag(x. the default.diag(x. 480 Chapter 3. 8]) >>> np. which is flattened and set as the k-th diagonal of the output. [0.reshape((3.3)) >>> x array([[0. 0. 7. diagonal Return specified diagonals. 2]. Examples >>> x = np. 8]]) >>> np. 5]) >>> np. Release 1.diag(x) array([0. 0]. Parameters v : array_like Input data. Routines . 4. 4. a positive (negative) k giving the number of the diagonal above (below) the main.1 trace Sum along diagonals. See Also: diag MATLAB work-alike for 1-D and 2-D arrays. 5].diag(np. Returns out : ndarray The 2-D output array. [0. k=1) array([1. 0]. [3. k : int. 7]) >>> np. [6. triu Upper triangle of an array. 0. k=0) Create a two-dimensional array with the flattened input as a diagonal.NumPy Reference. optional Diagonal to set. corresponds to the “main” diagonal. 8]]) numpy. trace Sum along diagonals.8. 4.diag(x)) array([[0. tril Lower triange of an array. k=-1) array([3.

tril(m. 0. M : int. 0.tri(3. 1. The default is 0. 0. k = 0 is the main diagonal. 0. [1.]]) numpy. 0. 1. [0. 0. 0]]) numpy.. 1. array([[1. 1. 2.. 1.. 1.4]]) array([[1. By default. Parameters m : array_like.tri(N. 0]. k=0) Lower triangle of an array. [ 1.2]. 0].. M=None.NumPy Reference.. 0]. 0]. Release 1. M is taken equal to N. 0. [0. [ 1. 0 otherwise. 0.2]... 0. The default is float. 1]]) >>> np. Array creation routines 481 . 1. k=0. 1.. Returns tri : ndarray of shape (N. [1. 0.. dtype=int) 0]. array([[ 0. 1. 0. in other words T[i.j] == 1 for i <= j + k. k : int. 0. 2]. 4]]) >>> np.1. [0.8. 0. 0.diagflat([1.1 Examples >>> np. k : int. 2. Examples >>> np. 0. 0]. 5. optional Data type of the returned array. 0. [0.. 0.. Return a copy of an array with elements above the k-th diagonal zeroed. 0.tri(3. while k < 0 is below it. dtype=<type ‘float’>) An array with ones at and below the given diagonal and zeros elsewhere. optional The sub-diagonal at and below which the array is filled.. -1) 0.diagflat([[1. shape (M. dtype : dtype. 3.].]. optional Number of columns in the array. optional 3. [3. [0. 5. 1) array([[0. 1. and k > 0 is above. 0. N) Input array. M) Array with its lower triangle filled with ones and zero elsewhere. Parameters N : int Number of rows in the array.

Such a matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde.8.6]. -1) array([[ 1. 0]. [ 0.6].12]]. [ 4.11. If N is not specified.[7.[10.9]. optional Order of (number of columns in) the output. The columns of the output matrix are decreasing powers of the input vector.5. 3].i .2. 12]]) numpy. shape (M. [ 4. the i-th output column is the input vector raised element-wise to the power of N . 11. 6].9].8. 2. Parameters x : array_like 1-D input array.tril([[1.vander(x.triu(m.[10.[4.2.3].1 Diagonal above which to zero elements. See Also: triu same thing. 8.1. See Also: tril lower triangle of an array Examples >>> np. N=None) Generate a Van der Monde matrix. 9].11. 12]]) numpy. 0]. N) Lower triangle of m. Routines . Release 1.[7. k=0) Upper triangle of an array. Return a copy of a matrix with the elements below the k-th diagonal zeroed.[4. Specifically. k = 0 (the default) is the main diagonal.8.5. 0]. Returns out : ndarray 482 Chapter 3.NumPy Reference. Please refer to the documentation for tril for further details.triu([[1. k < 0 is below it and k > 0 is above. -1) array([[ 0. Returns tril : ndarray.3].12]]. 8. 0. [ 0. [10. N : int. only for the upper triangle Examples >>> np. [ 7. 5. of same shape and data-type as m. 0. 0. a square array is returned (N = len(x)).

vander(x)) 48. 1]. [125. nested sequence.linalg. 5. 1].det(np. 4.vander(x) array([[ 1.1 Van der Monde matrix of order N. gdict]) Interpret the input as a matrix. 1]]) >>> x = np. ldict. 1]. 25. 1]]) >>> np. [ 9. 1. Build a matrix object from a string. 1]]) The determinant of a square Vandermonde matrix is the product of the differences between the values of the input vector: >>> np. Parameters data : array_like Input data. [ 27. 5. 1. 2. The first column is x^(N-1). 2. Returns mat : matrix data interpreted as a matrix. 1]. [25.1. or array. 3. 3. 1]. Examples >>> x = np. Unlike matrix. numpy.vander(x.1. 2.NumPy Reference. 5. copy=False). 1].000000000000043 >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1) 48 3. 2. the second x^(N-2) and so forth. N) array([[ 1. [ 8.mat(data.array([1. 5]) >>> N = 3 >>> np. [ 4. Equivalent to matrix(data. 1]. dtype=None) Interpret the input as a matrix. asmatrix does not make a copy if the input is already a matrix or an ndarray. dtype]) bmat(obj[. 1]. 1.7 The Matrix class mat(data[.array([1. [ 4. 5]) >>> np. 1]. 3.column_stack([x**(N-1-i) for i in range(N)]) array([[ 1. Release 1. [ 9. 1. 9. 3. 3. [25. 3. 2.8. Array creation routines 483 .

Parameters obj : str or array_like Input data. 4. 8. 6.mat(’3 np. 1. [C.r_[np.array([[1.8.bmat([[A.2 Array manipulation routines 3. 6. D]]) matrix([[1. 4]]) >>> m = np. 2]. 8]. 1. [5. [5. 4. 2. 0]]) 3. 2]. 2. which is a specialized 2-D array. 2. [3. 0]]) >>> np. 9. 2]. even if obj is a string. 1. 2]. D]]) matrix([[1. 2. See Also: matrix Examples >>> >>> >>> >>> A B C D = = = = np. 1. 2]. Release 1. C. 2. [3. 7. 2. 8]. [3. 2]. 4]]) numpy.1 Examples >>> x = np. 0]]) >>> np. 7.mat(’2 np.NumPy Reference. [3. 1.2. np.1 Basic operations 484 Chapter 3.mat(’7 1.mat(’1 np.c_[A. 4. 1 2 5 9 1’) 2’) 6’) 0’) All the following expressions construct the same block matrix: >>> np.c_[C. [1. 1. Returns out : matrix Returns a matrix object.D’) matrix([[1. 8]. B]. Routines .asmatrix(x) >>> x[0.bmat(’A. B]. [3. 9. 2].0] = 5 >>> m matrix([[5. [1. ldict=None. 2].bmat(obj. 4. Names of variables in the current scope may be referenced. gdict=None) Build a matrix object from a string. 2.bmat(np. nested sequence. 7. [1. 9. [5. or array. 6.B.

newshape : int or tuple of ints The new shape should be compatible with the original shape. ‘equiv’. preservena=False) Copies values from one array to another. Release 1.2. casting : {‘no’. • ‘unsafe’ means any data conversions may be done. • ‘equiv’ means only byte-order changes are allowed. src : array_like The array from which values are copied. Parameters a : array_like Array to be reshaped. optional Controls what kind of data casting may occur when copying. numpy.ma. 3. • ‘safe’ means only casts which can preserve values are allowed. ‘same_kind’. leaves any NA values in dst untouched. optional A boolean array which is broadcasted to match the dimensions of dst. ‘safe’. Return a flattened array. where=None. Array manipulation routines 485 . are allowed. This is similar to the “hard mask” feature in numpy. then the 3.NumPy Reference. • ‘no’ means the data types should not be cast at all.copyto(dst. ‘unsafe’}. order]) ndarray. optional If set to True. numpy.7. newshape.reshape(a. New in version 1.flat ndarray. src. broadcasting as necessary. preservena : bool. Raises a TypeError if the casting rule is violated. A 1-D iterator over the array. broadcasting as necessary.8. where : array_like of bool. If an integer. casting=’same_kind’.2. and selects elements to copy from src to dst wherever it contains the value True. src[. Parameters dst : ndarray The array into which values are copied. Return a copy of the array collapsed into one dimension. preservena]) Copies values from one array to another. where. order]) ravel(a[.1 copyto(dst. and if where is provided. it selects which elements to copy. newshape[.0. • ‘same_kind’ means only safe casts or casts within a kind. casting.flatten([order]) Gives a new shape to an array without changing its data.2 Changing array shape reshape(a. like float64 to float32. order=’C’) Gives a new shape to an array without changing its data.

or Fortran. and the last index changing slowest.zeros((10. 2)) >>> a array([[0. Release 1. 3). and place the elements into the reshaped array using this index order.contiguous) of the returned array.arange(6). it will be a copy. with the last axis index changing fastest. 2]. (2. ‘A’}. [2.reshape(a.ravel(a). let’s say you have an array: >>> a = np. [3. See Also: ndarray. you should assign the new shape to the shape attribute of the array: >>> a = np. then inserting the elements from the raveled array into the new array using the same kind of index ordering as was used for the raveling. >>> c = b. 1]. >>> np. (2. Returns reshaped_array : ndarray This will be a new view object if possible.view() >>> c. ‘F’ means to read / write the elements using Fortran-like index order. 1. In this case. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array. C-like order otherwise. Note there is no guarantee of the memory layout (C. ‘F’. One shape dimension can be -1. [4.1 result will be a 1-D array of that length.T # Taking a view makes it possible to modify the shape without modifying the # initial object. (2. optional Read the elements of a using this index order. 3)) # C-like index ordering array([[0. [2. with the first index changing fastest. 4. back to the first axis index changing slowest. Routines . For example. 1. 2)) # A transpose make the array non-contiguous >>> b = a.reshape((3. 5]]) >>> np. 1.NumPy Reference. 5]]) You can think of reshaping as first raveling the array (using the given index order). 3].reshape Equivalent method. 5]]) >>> np. 3)) # equivalent to C ravel then C reshape array([[0. 4. 5]]) 486 Chapter 3. ‘A’ means to read / write the elements in Fortran-like index order if a is Fortran contiguous in memory.reshape(np. and only refer to the order of indexing. the value is inferred from the length of the array and remaining dimensions. order=’F’) # Fortran-like index ordering array([[0. otherwise. order : {‘C’.shape = (20) AttributeError: incompatible shape for a non-contiguous array The order keyword gives the index ordering both for fetching the values from a.8. ‘C’ means to read / write the elements using C-like index order. 4. Notes It is not always possible to change the shape of an array without copying the data. and then placing the values into the output array. 3]. If you want an error to be raise if the data is copied. 2]. [3.reshape(a.

Returns 1d_array : ndarray Output of the same dtype as a. 4. and packed as a 1-D array. 5. order=’F’) array([[0. [2. and only refer to the order of axis indexing.2. Release 1. 5. 5]]) Examples >>> a = np. with the last axis index changing fastest.reshape(a. index ordering. ndarray. This can be generalized to multiple dimensions. 3.-1)) array([[1.3]. with the first index changing fastest. order : {‘C’. except for reversing the data when strides are negative. Notes In C-like (row-major) order. 6]]) # the unspecified value is inferred to be 2 numpy.flatten 1-D array copy of the elements of an array in row-major order.2. 3. optional The elements of a are read using this index order.reshape(a. (3. By default. order=’F’) array([1. [5.NumPy Reference. A copy is made only if needed. 6]) >>> np.size.flat 1-D iterator over an array. [3. and of shape (a. back to the first axis index changing slowest.).1 >>> np.’F’. ‘A’. 2. The elements in a are read in the order specified by order.5. Array manipulation routines 487 . is returned.reshape(a. ‘C’ index order is used. where row-major order implies that the index along the first axis varies slowest. or column-major. ‘C’ means to index the elements in C-like order. 2]. Parameters a : array_like Input array. ‘K’}. and the index along the last quickest. in two dimensions. order=’F’). 4.8. The opposite holds for Fortran-like. and the column index the quickest. 4]. A 1-D array. 4. 6. the row index varies the slowest. 6]) >>> np. [4. See Also: ndarray. 6) array([1. ‘A’ means to read the elements in Fortran-like index order if a is Fortran contiguous in memory.array([[1. (2. containing the elements of the input.reshape(np. order=’C’) Return a flattened array. ‘F’ means to index the elements in Fortran-like index order.ravel(a.6]]) >>> np. 1.ravel(a. and the last index changing slowest. C-like order otherwise. 3. 3). 3]. ‘K’ means to read the elements in the order they occur in memory. Note that the ‘C’ and ‘F’ options take no account of the memory layout of the underlying array. 2.

8. 0]) >>> a. order=’A’) [1 2 3 4 5 6] When order is ‘K’.array([[1. a array([[[ 0. 6.ravel(x. which acts similarly to. 1. 4. [ 1. 3) >>> x array([[1. 7. 4. 9. order=order). 3. [4.ravel(x. 10. but won’t reverse axes: >>> a = np. 2. 3.T) [1 4 2 5 3 6] >>> print np. 3]. 1. 5. 4]. 3.reshape(-1) [1 2 3 4 5 6] >>> print np. 2.NumPy Reference. 2. 7. 11]) ndarray. a array([2.reshape(2. [ 7. 0]) >>> a. See Also: flatten Return a copy of the array collapsed into one dimension.ravel(order=’K’) array([ 0.ravel(order=’K’) array([2.1 Examples It is equivalent to reshape(-1. 1. 2. it will preserve orderings that are neither ‘C’ nor ‘F’.ravel(order=’C’) array([2. 8. 6]]) >>> print np. 9. 5]]. Routines . order=’F’) [1 4 2 5 3 6] When order is ‘A’. flatiter Examples >>> x = np. 5. 8. Release 1. Python’s built-in iterator object.ravel(order=’C’) array([ 0. 3]. 2.T. 0]) >>> a = np.2). 5. 11]]]) >>> a. [[ 6.reshape(2. 1.3. This is a numpy.swapaxes(1. 8. 10]. [4. 11]) >>> a.arange(1.2). 6.flat A 1-D iterator over the array.flat[3] 488 Chapter 3. 10.flatiter instance. it will preserve the array’s ‘C’ or ‘F’ ordering: >>> print np.ravel(x. 9.arange(3)[::-1]. >>> x = np.arange(12). 1. 6]]) >>> x. 5. 7).ravel(x) [1 2 3 4 5 6] >>> print x. but is not a subclass of.

[3. 3].flat[3] 5 >>> type(x. 489 . Interchange two axes of an array.4]] = 1. [2.flat) <type ’numpy. 4]) 3.2. except that self is returned if self.NumPy Reference. 3. Same as self.2].ndim < 2.flatten() array([1.flatten(’F’) array([1. axis2) ndarray. 1. 3. ‘F’. Release 1. flat A 1-D flat iterator over the array. Parameters order : {‘C’.array([[1. x array([[3. 3.flat = 3. Permute the dimensions of an array. start]) swapaxes(a. 4]. 3]. Fortran (column-major) order. Returns y : ndarray A copy of the input array. 3.flatten(order=’C’) Return a copy of the array collapsed into one dimension. flattened to one dimension.flatiter’> An assignment example: >>> x. [3. 4]) >>> a. axis[.transpose().T. 3]]) ndarray.1 4 >>> x. until it lies in a given position. [3. 2. optional Whether to flatten in C (row-major).2. See Also: ravel Return a flattened array. The default is ‘C’. 1. 2. [3. 5]. 3]]) >>> x. axes]) 3. x array([[3. axis1. Examples >>> a = np.3 Transpose-like operations rollaxis(a.8. 6]]) >>> x.flat[[1.T transpose(a[. or preserve the C/Fortran ordering from a. ‘A’}.T array([[1.4]]) >>> a. Array manipulation routines Roll the specified axis backwards.

1. 5) np.3]]) >>> np. Returns res : ndarray Output array.rollaxis(a.swapaxes(a. 1).rollaxis(a. axis.NumPy Reference. See Also: roll Roll the elements of an array by a number of positions along a given axis.rollaxis(a. optional The axis is rolled until it lies before this position.6)) np. Examples >>> x = np. axis : int The axis to roll backwards.4. 6) np. results in a “complete” roll. 4).1) array([[1].8. 4) numpy. a = np.2. 2). Parameters a : ndarray Input array. until it lies in a given position.0. axis2 : int Second axis. axis1 : int First axis.5.shape 5. Returns a_swapped : ndarray If a is an ndarray. 0.array([[1. otherwise a new array is created.shape 3.swapaxes(x. start : int. >>> (5. start=0) Roll the specified axis backwards. 6. Parameters a : array_like Input array.rollaxis(a. Release 1. The default. axis2) Interchange two axes of an array.ones((3. 4. then a view of a is returned. Examples >>> >>> (3. 490 Chapter 3.1 numpy. 3. 4. axis1.shape 6. >>> (3. Routines . The positions of the other axes do not change relative to one another.

[ 2.array([[[0.].[6.[[4. [6. axes=None) Permute the dimensions of an array. axes : list of ints. [2. [3]]) >>> x = np.swapaxes(x.]) >>> x array([ 1. 7]]]) >>> np. 4].ndim < 2.NumPy Reference. A view is returned whenever possible. 5].[2.2)) >>> x 3.2. 6]]. except that self is returned if self..T Same as self... 7]]]) ndarray. 2...1]. Examples >>> x = np.. 5]. 2.array([1. [[1. 4..8. otherwise permute the axes according to the values given.2) array([[[0.. 4.]]) >>> x array([[ 1.transpose().arange(4).1 [2].2. [3.].transpose(a.T array([ 1..]]) >>> x. See Also: rollaxis Examples >>> x = np..4. [[4. 2. 3]]. Release 1.3.3]].7]]]) >>> x array([[[0.]]) >>> x = np. Array manipulation routines 491 .[3.]) >>> x.2.].. [ 3..array([[1.T array([[ 1. 3. 4.5].. optional By default. 3..]) numpy. 1]. 4. reverse the dimensions.. [2. Parameters a : array_like Input array.reshape((2.0. Returns p : ndarray a with its axes permuted.4. 3.

atleast_1d(1.reshape(3.]. array([3. 8.4 Changing number of dimensions atleast_1d(*arys) atleast_2d(*arys) atleast_3d(*arys) broadcast broadcast_arrays(*args) expand_dims(a. Parameters arys1. 2]. arys2. [ 3. 3]]) >>> x = np. Broadcast any number of arrays against each other. . 4])] 492 Chapter 3. 2. each with a.0) array([ 1. 3) 3.. : array_like One or more input arrays. whilst higher-dimensional inputs are preserved. numpy. 5. 7. 1.8. Copies are made only if necessary. [2. 1].].arange(9. Returns ret : ndarray An array. 3)) >>> np.. 4.shape (2. or sequence of arrays. Routines . Remove single-dimensional entries from the shape of an array.atleast_1d(x) array([[ 0. View inputs as arrays with at least two dimensions.ones((1. See Also: atleast_2d. 4]) [array([1]).atleast_1d(*arys) Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays.ndim >= 1.]]) >>> np.transpose(x. 0. [ 6.0). View inputs as arrays with at least three dimensions.. axis) squeeze(a[.2..NumPy Reference. (1.. 2.. [1. 2)).1 array([[0.atleast_1d(x) is x True >>> np. 3]]) >>> np. Expand the shape of an array.transpose(x) array([[0.. axis]) Convert inputs to arrays with at least one dimension.. 1. Release 1. atleast_3d Examples >>> np. [3.3) >>> np. Produce an object that mimics broadcasting.]) >>> x = np.atleast_1d(1.

: ndarray An array. : array_like One or more array-like sequences. array([[1. 2. 1) 3.. Copies are avoided where possible.. each with a.. arys2. 2]. Parameters arys1. Release 1.atleast_3d(*arys) View inputs as arrays with at least three dimensions.NumPy Reference.atleast_2d(x) array([[ 0. and a 2-D array of shape (M. Copies are avoided where possible.ndim >= 3. array([[1.atleast_3d(x).. 3. Arrays that already have two or more dimensions are preserved. and views with three or more dimensions are returned. arys2. or tuple of arrays.8.0) >>> np. Returns res. See Also: atleast_1d. [[1.arange(3.atleast_2d(3.1 numpy. See Also: atleast_1d.shape (1. N.. 1). : array_like One or more array-like sequences.. [1. or tuple of arrays.2. 2]])] numpy.atleast_2d(x).]]) >>> np. Non-array inputs are converted to arrays. .]]]) >>> x = np.atleast_2d(1. .arange(3. each with a.atleast_3d(3. N) becomes a view of shape (M. 1).0) array([[[ 3. 2]]).. atleast_3d Examples >>> np.atleast_2d(*arys) View inputs as arrays with at least two dimensions. Array manipulation routines 493 . 2]]) [array([[1]]). .]]) >>> x = np.0) array([[ 3. N. Returns res1.base is x True >>> np.0) >>> np.) becomes a view of shape (1. atleast_2d Examples >>> np. Non-array inputs are converted to arrays. res2. For example.ndim >= 2. . 1. and views with two or more dimensions are returned. : ndarray An array. res2. a 1-D array of shape (N. Parameters arys1.. Arrays that already have three or more dimensions are preserved...

8.array([[1]. y) >>> out = np. 1) >>> np.empty(b.arange(12. Parameters in1.. [[1. [[[1. in2. 5.1 >>> x = np. 1) [[[1] [2]]] (1.0).. 1) [[[1 2]]] (1. [ 6. Examples Manually adding two vectors. [[[1] [2]]] (1. print arr. using broadcasting: >>> x = np.. 9.3) >>> np. and may be used as an iterator. Release 1... 2) class numpy. 8. 2]]. [ 7..v) in b] >>> out array([[ 5. [7. 2. it has shape and nd properties.flat = [u+v for (u. 3. Returns b : broadcast object Broadcast the input parameters against one another. .” Shape of broadcasted result. 2].. 2. 7.8.reshape(4. 6. 7. 7.. 8]..shape) >>> out.]]) Compare against built-in broadcasting: >>> x + y array([[5...base is x True >>> for arr in np. 6]) >>> b = np. Total size of broadcasted result. 2]]]): .].NumPy Reference. Routines .atleast_3d(x). [3]]) >>> y = np. 9]]) Attributes index iters shape size 494 current index in broadcasted result tuple of iterators along self‘s “components. 1. Amongst others.shape (4. [6. 7]. : array_like Input parameters.broadcast(x.atleast_3d(x).broadcast Produce an object that mimics broadcasting.]. Chapter 3. and return an object that encapsulates the result. arr..array([4.atleast_3d([1. [2]. 8.shape . 6.

shape 3) broadcast.index 0 >>> b.NumPy Reference. y) b.size Total size of broadcasted result.array([[1].2. Examples >>> >>> >>> >>> 9 x = np. 6)) >>> b.array([[4]. 2.shape Shape of broadcasted result.index current index in broadcasted result Examples >>> x = np. y) >>> b.broadcast(x. See Also: numpy. or raise StopIteration Reset the broadcasted result’s iterator(s). [6]]) b = np.index 3 broadcast. x = np.next() -> the next value. y) row.broadcast(x.array([1. 3]) y = np. [2].next().iters row. col.next(). 5.array([[4]. x = np. [6]]) b = np. col = b. Release 1.array([4. (1.next() 4) broadcast. [5]. 5).next() ((1.iters tuple of iterators along self‘s “components. Examples >>> >>> >>> >>> (3. 2. b.flatiter Examples >>> >>> >>> >>> >>> (1. 6]) >>> b = np. one for each “component” of self. 2. y) b. 495 .array([[4]. [6]]) b = np. b.array([1. Array manipulation routines x.size Methods next reset() 3.” Returns a tuple of numpy. [5].flatiter objects. 3]) y = np.broadcast(x. 4).8. [3]]) >>> y = np.next(). (1. [5].1 broadcast. 3]) y = np.array([1.broadcast(x.

y)] [array([[1.broadcast(x. [2. They are typically not contiguous. 3].array([[1.next(). (2. 3]]). 1.8. Parameters None Returns None Examples >>> x = np. 3]. 3]]). >>> [np.broadcast_arrays(*args) Broadcast any number of arrays against each other. or raise StopIteration broadcast. [1. [6]] >>> b = np. 2.[3]]) >>> np.next() -> the next value. Parameters ‘*args‘ : array_likes The arrays to broadcast. 3]])] 496 Chapter 3. 2. y) >>> b. y) [array([[1. [1.next() ((1. array([[1.1 broadcast. 3]])] Here is a useful idiom for getting contiguous copies instead of non-contiguous views. Examples >>> x = np. 1]. more than one element of a broadcasted array may refer to a single memory location.reset() Reset the broadcasted result’s iterator(s). [3.[2]. 3].next x. 2. 2]. If you need to write to the arrays. 4).next(). 3. b.index 3 >>> b. 3]. 4)) >>> b. 2. b.array([1. 2. 1. 2. [2.array(a) for a in np. make copies first. [5].2. Routines . 2.array([[1]. 1].NumPy Reference. 2]. 3.index 0 numpy. [3. Furthermore. [1. 4). Release 1.reset() >>> b. (3. Returns broadcasted : list of arrays These arrays are views on the original arrays. 3]) >>> y = np.index 0 >>> b. array([[1.broadcast_arrays(x.broadcast_arrays(x. 2. [1.array([[4].3]]) >>> y = np. 2.

an error is raised. Parameters a : array_like Input data. atleast_2d.shape (1. These are the same objects: >>> np.:] or x[np.shape (2.newaxis]: >>> y = np.array([1. 2) >>> y = np. Array manipulation routines 497 . corresponding to a given position in the array shape.) The following is equivalent to x[np. axis=1) >>> y array([[1]. Selects a subset of the single-dimensional entries in the shape.8.2. See Also: doc. The number of dimensions is one greater than that of the input array.2]) >>> x.newaxis. Returns res : ndarray Output array. 2]]) >>> y. Returns squeezed : ndarray 3. Insert a new axis. If an axis is selected with shape entry greater than one. axis : int Position (amongst axes) where new axis is to be inserted.expand_dims(x. Release 1.7.indexing.newaxis] Note that some examples may use None instead of np. 1) # Equivalent to x[:. atleast_3d Examples >>> x = np.NumPy Reference. optional New in version 1.shape (2. axis) Expand the shape of an array.0. axis=0) >>> y array([[1.newaxis is None True numpy. axis=None) Remove single-dimensional entries from the shape of an array.expand_dims(x.squeeze(a.expand_dims(a.1 numpy. [2]]) >>> y.newaxis. atleast_1d. Parameters a : array_like Input array. axis : None or int or tuple of ints.

numpy.shape (3. Release 1. ‘F’}. dtype : data-type. axis=(2.shape (1. order]) asanyarray(a[. but pass ndarray subclasses through. optional Whether to use row-major (‘C’) or column-major (‘F’ for FORTRAN) memory representation.) >>> np. [1]. Convert the input to an ndarray. dtype. No copy is performed if the input is already an ndarray.2. Parameters a : array_like Input data. Routines . This includes lists.8.array([[[0].5 Changing kind of array asarray(a[. If a is a subclass of ndarray.asarray(a. 498 Chapter 3. optional By default. 3. asfarray Convert input to a floating point ndarray. [2]]]) >>> x. Return an ndarray of the provided type that satisfies requirements. ascontiguousarray Convert input to a contiguous array.1 The input array.squeeze(x). order : {‘C’. order]) asmatrix(data[.squeeze(x. Defaults to ‘C’. See Also: asanyarray Similar function which passes through subclasses. order=None) Convert the input to an array. dtype]) asscalar(a) require(a[. but with with all or a subset of the dimensions of length 1 removed. dtype. Convert an array of size 1 to its scalar equivalent. dtype]) asfortranarray(a[. Examples >>> x = np. This is always a itself or a view into a. the data-type is inferred from the input data. dtype=None.)). in any form that can be converted to an array. Return an array laid out in Fortran order in memory. Return an array converted to a float type. dtype. requirements]) Convert the input to an array. tuples of tuples.NumPy Reference. tuples of lists and ndarrays. 1) >>> np. Interpret the input as a matrix. 3) 3. a base class ndarray is returned. lists of tuples. tuples. Returns out : ndarray Array interpretation of a. dtype]) asfarray(a[.shape (1.

Release 1. Array manipulation routines 499 . ‘F’}.8.asarray(a. lists of tuples. This includes scalars. asarray_chkfinite Similar function which checks input for NaNs and Infs.ndarray) True >>> a = np. tuples.array([1.asarray(a. 2]. dtype=np.asanyarray(a) is a True numpy. 2]) >>> np. Defaults to ‘C’.1 asfortranarray Convert input to an ndarray with column-major memory order.float32) is a True >>> np. optional Whether to use row-major (‘C’) or column-major (‘F’) memory representation.asarray(a) is a False >>> np.matrix([[1. the data-type is inferred from the input data.asarray(a) is a True If dtype is set. 2] >>> np. order : {‘C’. but pass ndarray subclasses through. np. ndarray subclasses are not passed through: >>> issubclass(np. Parameters a : array_like Input data. and ndarrays. dtype=None. lists. dtype : data-type.2. fromiter Create an array from an iterator.float32) >>> np. tuples of tuples. in any form that can be converted to an array. 2]) Existing arrays are not copied: >>> a = np.float64) is a False Contrary to asanyarray. 3. dtype=np. order=None) Convert the input to an ndarray. Examples Convert a list into an array: >>> a = [1. optional By default.NumPy Reference.matrix. array is copied only if dtype does not match: >>> a = np. 2]]) >>> np.asanyarray(a. tuples of lists.array([1.asarray(a) array([1. fromfunction Construct an array by executing a function on grid positions. dtype=np.

Examples >>> x = np. Unlike matrix. it is returned as-is and no copy is performed.asanyarray(a) is a True numpy. 4]]) 500 Chapter 3. fromfunction Construct an array by executing a function on grid positions.1 Returns out : ndarray or an ndarray subclass Array interpretation of a. fromiter Create an array from an iterator. Examples Convert a list into an array: >>> a = [1.asanyarray(a) array([1. 2] >>> np. 2]. Release 1. Equivalent to matrix(data. asmatrix does not make a copy if the input is already a matrix or an ndarray.matrix([1. 2]) >>> np.array([[1. asfarray Convert input to a floating point ndarray. copy=False). Returns mat : matrix data interpreted as a matrix. asarray_chkfinite Similar function which checks input for NaNs and Infs. dtype=None) Interpret the input as a matrix. If a is an ndarray or a subclass of ndarray. Routines . See Also: asarray Similar function which always returns ndarrays. ascontiguousarray Convert input to a contiguous array.NumPy Reference. Parameters data : array_like Input data. [3. asfortranarray Convert input to an ndarray with column-major memory order. 2]) Instances of ndarray subclasses are passed through as-is: >>> a = np.8.asmatrix(data.

dtype=’float’) array([ 2. See Also: ascontiguousarray Convert input to a contiguous (C order) array. Examples >>> np. Returns out : ndarray The input a as a float ndarray. asanyarray Convert input to an ndarray with either row or column-major memory order. or column-major. 3]. dtype : str or dtype object. require Return an ndarray that satisfies requirements. [3. 3]) array([ 2. 2]. Array manipulation routines 501 .1 >>> m = np.]) >>> np.asfarray([2.]) numpy. dtype=<type ‘numpy. dtype=None) Return an array laid out in Fortran order in memory. 3. 3].]) >>> np.0] = 5 >>> m matrix([[5. optional Float type code to coerce input array a. optional By default.. Parameters a : array_like The input array. Returns out : ndarray The input a in Fortran.asfarray(a.asmatrix(x) >>> x[0. If dtype is one of the ‘int’ dtypes. 3.float64’>) Return an array converted to a float type.asfortranarray(a. order. 3.8. dtype : str or dtype object.asfarray([2. Release 1..2.asfarray([2.NumPy Reference. dtype=’int8’) array([ 2. 4]]) numpy. it is replaced with float64. the data-type is inferred from the input data.. 3. Parameters a : array_like Input array.

flags[’F_CONTIGUOUS’] True numpy.ensure an array that owns its own data See Also: asarray Convert input to an ndarray.array([24])) 24 numpy. the default data-type is float64). Returns out : scalar Scalar representation of a. 502 Chapter 3. Routines . Examples >>> np.ensure a data-type aligned array • ‘WRITEABLE’ (‘W’) . Release 1.reshape(2. Parameters a : array_like The object to be converted to a type-and-requirement-satisfying array.require(a.asscalar(a) Convert an array of size 1 to its scalar equivalent.ensure a writable array • ‘OWNDATA’ (‘O’) .asscalar(np. The output data type is the same type returned by the input’s item method. dtype=None. Examples >>> x = np. dtype : data-type The required data-type.1 ndarray.ensure a C-contiguous array • ‘ALIGNED’ (‘A’) .3) >>> y = np. Parameters a : ndarray Input array of size 1. requirements : str or list of str The requirements list can be any of the following • ‘F_CONTIGUOUS’ (‘F’) .asfortranarray(x) >>> x.ensure a Fortran-contiguous array • ‘C_CONTIGUOUS’ (‘C’) . requirements=None) Return an ndarray of the provided type that satisfies requirements. This function is useful to be sure that an array with the correct flags is returned for passing to compiled code (perhaps through ctypes).NumPy Reference.8.arange(6).flags Information about the memory layout of the array.flags[’F_CONTIGUOUS’] False >>> y.

. Stack arrays in sequence depth wise (along third axis). Parameters tup : sequence of 1-D or 2-D arrays. axis]) dstack(tup) hstack(tup) vstack(tup) Stack 1-D arrays as columns into a 2-D array.)[. ndarray. Release 1.reshape(2. ascontiguousarray Convert input to a contiguous array. Returns stacked : 2-D array 3. 1-D arrays are turned into 2-D columns first. a2. All of them must have the same first dimension.flags Information about the memory layout of the array. . just like with hstack. ’W’. requirements=[’A’.1 asanyarray Convert to an ndarray.6 Joining arrays column_stack(tup) concatenate((a1.3) >>> x.require(x.float32.flags C_CONTIGUOUS : True F_CONTIGUOUS : False OWNDATA : False WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False >>> y = np. Arrays to stack. Examples >>> x = np. 2-D arrays are stacked as-is. Join a sequence of arrays together. but pass through ndarray subclasses. dtype=np. Stack arrays in sequence horizontally (column wise). ’F’]) >>> y.8.arange(6)..NumPy Reference.flags C_CONTIGUOUS : False F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False 3. asfortranarray Convert input to an ndarray with column-major memory order.2. Stack arr