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 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 a ndarray can be accessed and modified by indexing or slicing the array (using for example N integers), and via the methods and attributes of the ndarray.
Different 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 a Python container-like syntax:
>>> x[1,2]
6
For example slicing can produce views of the array:
>>> y = x[:,1]
>>> y[0] = 9
>>> x
array([[1, 9, 3],
[4, 5, 6]])
New arrays can be constructed using the routines detailed in Array creation routines, and also by using the low-level ndarray constructor:
ndarray (shape[, dtype, buffer, offset, ...]) | 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 or a floating point number, etc.). |
Arrays can be indexed using an extended Python slicing syntax, array[selection]. Similar syntax is also used for accessing fields in a record array.
See also
An instance of class ndarray consists of a contiguous one-dimensional segment of computer memory (owned by the array, or by some other object), combined with an indexing scheme that maps N integers into the location of an item in the block. The ranges in which the indices can vary is specified by the shape of the array. How many bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.
A segment of memory is inherently 1-dimensional, and there are many different schemes of arranging the items of an N-dimensional array to a 1-dimensional block. Numpy is flexible, and ndarray objects can accommodate any strided indexing scheme. In a strided scheme, the N-dimensional index corresponds to the offset (in bytes)
from the beginning of the memory block associated with the array. Here, are integers which specify the strides of the array. The column-major order (used for example in the Fortran language and in Matlab) and row-major order (used in C) are special cases of the strided scheme, and correspond to the strides:
Both the C and Fortran orders are contiguous, i.e. single-segment, memory layouts, in which every part of the memory block can be accessed by some combination of the indices.
Data in new ndarrays is in the row-major (C) order, unless otherwise specified, but for example basic array slicing often produces views in a different scheme.
Note
Several algorithms in NumPy work on arbitrarily strided arrays. However, some algorithms require single-segment arrays. When an irregularly strided array is passed in to such algorithms, a copy is automatically made.
Array attributes reflect information that is intrinsic to the array itself. Generally, accessing an array through its attributes allows you to get and sometimes set intrinsic properties of the array without creating a new array. The exposed attributes are the core parts of an array and only some of them can be reset meaningfully without creating a new array. Information on each attribute is given below.
The following attributes contain information about the memory layout of the array:
ndarray.flags | Information about the memory layout of the array. |
ndarray.shape | Tuple of array dimensions. |
ndarray.strides | Tuple of bytes to step in each dimension. |
ndarray.ndim | Number of array dimensions. |
ndarray.data | Buffer object pointing to the start of the data. |
ndarray.size | Number of elements in the array. |
ndarray.itemsize | Length of one element in bytes. |
ndarray.nbytes | Number of bytes in the array. |
ndarray.base | Base object if memory is from some other object. |
Note
XXX: update and check these docstrings.
See also
The data type object associated with the array can be found in the dtype attribute:
ndarray.dtype | Data-type for the array. |
Note
XXX: update the dtype attribute docstring: setting etc.
ndarray.T | Same as self.transpose() except self is returned for self.ndim < 2. |
ndarray.real | The real part of the array. |
ndarray.imag | The imaginary part of the array. |
ndarray.flat | A 1-d flat iterator. |
ndarray.ctypes | A ctypes interface object. |
__array_priority__ |
See also
__array_interface__ | Python-side of the array interface |
__array_struct__ | C-side of the array interface |
ndarray.ctypes | A ctypes interface object. |
Note
XXX: update and check these docstrings.
An ndarray object has many methods which operate on or with the array in some fashion, typically returning an array result. These methods are explained below.
For the following methods there are also corresponding functions in numpy: all, any, argmax, argmin, argsort, choose, clip, compress, copy, cumprod, cumsum, diagonal, imag, max, mean, min, nonzero, prod, ptp, put, ravel, real, repeat, reshape, round, searchsorted, sort, squeeze, std, sum, swapaxes, take, trace, transpose, var.
ndarray.item () | Copy the first element of array to a standard Python scalar and return it. The array must be of size one. |
ndarray.tolist () | Return the array as a possibly nested list. |
ndarray.itemset () | |
ndarray.tostring ([order]) | Construct a Python string containing the raw data bytes in the array. |
ndarray.tofile (fid[, sep, format]) | Write array to a file as text or binary. |
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. |
ndarray.dumps () | Returns the pickle of the array as a string. pickle.loads or numpy.loads will convert the string back to an array. |
ndarray.astype (t) | Copy of the array, cast to a specified type. |
ndarray.byteswap (inplace) | Swap the bytes of the array elements |
ndarray.copy ([order]) | Return a copy of the array. |
ndarray.view ([dtype, type]) | New view of array with the same data. |
ndarray.getfield (dtype, offset) | Returns a field of the given array as a certain type. A field is a view of the array data with each itemsize determined by the given type and the offset into the current array. |
ndarray.setflags ([write, align, uic]) | |
ndarray.fill (value) | Fill the array with a scalar value. |
Note
XXX: update and check these docstrings.
For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple.
ndarray.reshape (shape[, order]) | Returns an array containing the same data with a new shape. |
ndarray.resize (new_shape[, refcheck, order]) | Change shape and size of array in-place. |
ndarray.transpose (*axes) | Returns a view of ‘a’ with axes transposed. If no axes are given, or None is passed, switches the order of the axes. For a 2-d array, this is the usual matrix transpose. If axes are given, they describe how the axes are permuted. |
ndarray.swapaxes (axis1, axis2) | Return a view of the array with axis1 and axis2 interchanged. |
ndarray.flatten ([order]) | Collapse an array into one dimension. |
ndarray.ravel ([order]) | Return a flattened array. |
ndarray.squeeze () | Remove single-dimensional entries from the shape of a. |
For array methods that take an axis keyword, it defaults to None. If axis is None, then the array is treated as a 1-D array. Any other value for axis represents the dimension along which the operation should proceed.
ndarray.take (indices[, axis, out, mode]) | Return an array formed from the elements of a at the given indices. |
ndarray.put (indices, values[, mode]) | Set a.flat[n] = values[n] for all n in indices. |
ndarray.repeat (repeats[, axis]) | Repeat elements of an array. |
ndarray.choose (choices[, out, mode]) | Use an index array to construct a new array from a set of choices. |
ndarray.sort ([axis, kind, order]) | Sort an array, in-place. |
ndarray.argsort ([axis, kind, order]) | Returns the indices that would sort this array. |
ndarray.searchsorted (v[, side]) | Find indices where elements of v should be inserted in a to maintain order. |
ndarray.nonzero () | Return the indices of the elements that are non-zero. |
ndarray.compress (condition[, axis, out]) | Return selected slices of this array along given axis. |
ndarray.diagonal ([offset, axis1, axis2]) | Return specified diagonals. |
Many of these methods take an argument named axis. In such cases,
The parameter dtype specifies the data type over which a reduction operation (like summing) should take place. The default reduce data type is the same as the data type of self. To avoid overflow, it can be useful to perform the reduction using a larger data type.
For several methods, an optional out argument can also be provided and the result will be placed into the output array given. The out argument must be an ndarray and have the same number of elements. It can have a different data type in which case casting will be performed.
ndarray.argmax ([axis, out]) | Return indices of the maximum values along the given axis of a. |
ndarray.min ([axis, out]) | Return the minimum along a given axis. |
ndarray.argmin ([axis, out]) | Return indices of the minimum values along the given axis of a. |
ndarray.ptp ([axis, out]) | Peak to peak (maximum - minimum) value along a given axis. |
ndarray.clip (a_min, a_max[, out]) | Return an array whose values are limited to [a_min, a_max]. |
ndarray.conj () | Return an array with all complex-valued elements conjugated. |
ndarray.round ([decimals, out]) | Return an array rounded a to the given number of decimals. |
ndarray.trace ([offset, axis1, axis2, ...]) | Return the sum along diagonals of the array. |
ndarray.sum ([axis, dtype, out]) | Return the sum of the array elements over the given axis. |
ndarray.cumsum ([axis, dtype, out]) | Return the cumulative sum of the elements along the given axis. |
ndarray.mean ([axis, dtype, out]) | Returns the average of the array elements along given axis. |
ndarray.var ([axis, dtype, out, ...]) | Returns the variance of the array elements, along given axis. |
ndarray.std ([axis, dtype, out, ...]) | Returns the standard deviation of the array elements along given axis. |
ndarray.prod ([axis, dtype, out]) | Return the product of the array elements over the given axis |
ndarray.cumprod ([axis, dtype, out]) | Return the cumulative product of the elements along the given axis. |
ndarray.all ([axis, out]) | Returns True if all elements evaluate to True. |
ndarray.any ([axis, out]) | Check if any of the elements of a are true. |
Note
XXX: write all attributes explicitly here instead of relying on the auto* stuff?
Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results.
Each of the arithmetic operations (+, -, *, /, //, %, divmod(), ** or pow(), <<, >>, &, ^, |, ~) and the comparisons (==, <, >, <=, >=, !=) is equivalent to the corresponding universal function (or ufunc for short) in Numpy. For more information, see the section on Universal Functions.
Comparison operators:
ndarray.__lt__ () | x.__lt__(y) <==> x<y |
ndarray.__le__ () | x.__le__(y) <==> x<=y |
ndarray.__gt__ () | x.__gt__(y) <==> x>y |
ndarray.__ge__ () | x.__ge__(y) <==> x>=y |
ndarray.__eq__ () | x.__eq__(y) <==> x==y |
ndarray.__ne__ () | x.__ne__(y) <==> x!=y |
Truth value of an array (bool):
ndarray.__nonzero__ () | x.__nonzero__() <==> x != 0 |
Note
Truth-value testing of an array invokes ndarray.__nonzero__, which raises an error if the number of elements in the the array is larger than 1, because the truth value of such arrays is ambiguous. Use .any() and .all() instead to be clear about what is meant in such cases. (If the number of elements is 0, the array evaluates to False.)
Unary operations:
ndarray.__neg__ () | x.__neg__() <==> -x |
ndarray.__pos__ () | x.__pos__() <==> +x |
ndarray.__abs__ () <]) | |
ndarray.__invert__ () | x.__invert__() <==> ~x |
Arithmetic:
ndarray.__add__ () | x.__add__(y) <==> x+y |
ndarray.__sub__ () | x.__sub__(y) <==> x-y |
ndarray.__mul__ () | x.__mul__(y) <==> x*y |
ndarray.__div__ () | x.__div__(y) <==> x/y |
ndarray.__truediv__ () | x.__truediv__(y) <==> x/y |
ndarray.__floordiv__ () | x.__floordiv__(y) <==> x//y |
ndarray.__mod__ () | x.__mod__(y) <==> x%y |
ndarray.__divmod__ (y) <, y) | |
ndarray.__pow__ (y[, z]) <, y[, z]) | |
ndarray.__lshift__ () | x.__lshift__(y) <==> x<<y |
ndarray.__rshift__ () | x.__rshift__(y) <==> x>>y |
ndarray.__and__ () | x.__and__(y) <==> x&y |
ndarray.__or__ () | x.__or__(y) <==> x|y |
ndarray.__xor__ () | x.__xor__(y) <==> x^y |
Note
Arithmetic, in-place:
ndarray.__iadd__ () | x.__iadd__(y) <==> x+y |
ndarray.__isub__ () | x.__isub__(y) <==> x-y |
ndarray.__imul__ () | x.__imul__(y) <==> x*y |
ndarray.__idiv__ () | x.__idiv__(y) <==> x/y |
ndarray.__itruediv__ () | x.__itruediv__(y) <==> x/y |
ndarray.__ifloordiv__ () | x.__ifloordiv__(y) <==> x//y |
ndarray.__imod__ () | x.__imod__(y) <==> x%y |
ndarray.__ipow__ () | x.__ipow__(y) <==> x**y |
ndarray.__ilshift__ () | x.__ilshift__(y) <==> x<<y |
ndarray.__irshift__ () | x.__irshift__(y) <==> x>>y |
ndarray.__iand__ () | x.__iand__(y) <==> x&y |
ndarray.__ior__ () | x.__ior__(y) <==> x|y |
ndarray.__ixor__ () | x.__ixor__(y) <==> x^y |
Warning
In place operations will perform the calculation using the precision decided by the data type of the two operands, but will silently downcast the result (if necessary) so it can fit back into the array. Therefore, for mixed precision calculations, A {op}= B can be different than A = A {op} B. For example, suppose a = ones((3,3)). Then, a += 3j is different than a = a + 3j: While they both perform the same computation, a += 3 casts the result to fit back in a, whereas a = a + 3j re-binds the name a to the result.
For standard library functions:
ndarray.__copy__ ([order]) | Return a copy of the array. |
ndarray.__deepcopy__ () | a.__deepcopy__() -> Deep copy of array. |
ndarray.__reduce__ () | For pickling. |
ndarray.__setstate__ (version, shape, dtype, ...) | For unpickling. |
Basic customization:
ndarray.__new__ () | T.__new__(S, ...) -> a new object with type S, a subtype of T |
ndarray.__array__ () | a.__array__(|dtype) -> reference if type unchanged, copy otherwise. |
ndarray.__array_wrap__ () | a.__array_wrap__(obj) -> Object of same type as a from ndarray obj. |
Container customization: (see Indexing)
ndarray.__len__ () <]) | |
ndarray.__getitem__ () | x.__getitem__(y) <==> x[y] |
ndarray.__setitem__ () | x.__setitem__(i, y) <==> x[i]=y |
ndarray.__getslice__ () | x.__getslice__(i, j) <==> x[i:j] |
ndarray.__setslice__ () | x.__setslice__(i, j, y) <==> x[i:j]=y |
ndarray.__contains__ () | x.__contains__(y) <==> y in x |
Conversion; the operations complex, int, long, float, oct, and hex. They work only on arrays that have one element in them and return the appropriate scalar.
ndarray.__int__ () <]) | |
ndarray.__long__ () <]) | |
ndarray.__float__ () <]) | |
ndarray.__oct__ () <]) | |
ndarray.__hex__ () <]) |
String representations:
ndarray.__str__ () <]) | |
ndarray.__repr__ () <]) |