## NumPy ndarray: Complete Guide | Learn with Examples

NumPy ndarray — это многомерный массив, который позволяет хранить и оперировать данными, представленными в виде числовых массивов. Он описывает набор числовых значений, которые упорядочены в виде равномерной сетки. Numpy ndarray имеет множество функций и методов для выполнения различных операций с данными, включая арифметические операции, операции логического сравнения, сортировку, фильтрацию и многое другое.

Рассмотрим пример создания ndarray массива:

import numpy as np

# Создание одномерного ndarray массива

arr1 = np.array([1, 2, 3, 4, 5])

# Создание двумерного ndarray массива

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

Как видно из примера, создание массива осуществляется при помощи функции np.array(), которой передается список или кортеж чисел. Также можно создавать многомерные массивы, передавая список из списков.

Операции с массивами в NumPy ndarray могут выполняться с использованием разнообразных функций и методов.

Рассмотрим пример умножения двух ndarray массивов:

import numpy as np

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

b = np.array([[5, 6], [7, 8]])

Результатом выполнения данного примера является ndarray массив, полученный умножением массива a на массив b при помощи метода np.dot().

В NumPy также можно выполнить различные математические операции с корректной обработкой элементов массива, в том числе сложение, вычитание, умножение и деление.

import numpy as np

a = np.array([1, 2, 3])

b = np.array([4, 5, 6])

Как видно из примера, при выполнении арифметических операций с ndarray массивами, результатом является новый ndarray массив, содержащий результат операции над элементами исходных массивов.

Также NumPy ndarray предоставляет удобный интерфейс для фильтрации данных.

import numpy as np

a = np.array([1, 2, 3, 4, 5])

## 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* non-negative integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype) , one of which is associated with each ndarray.

As with other container objects in Python, the contents of an ndarray can be accessed and modified by indexing or slicing the array (using, for example, *N* integers), and via the methods and attributes of the ndarray .

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

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) >>> x.shape (2, 3) >>> x.dtype dtype('int32')

The array can be indexed using Python container-like syntax:

>>> # The element of x in the *second* row, *third* column, namely, 6. >>> x[1, 2] 6

For example slicing can produce views of the array:

>>> y = x[:,1] >>> y array([2, 5], dtype=int32) >>> y[0] = 9 # this also changes the corresponding element in x >>> y array([9, 5], dtype=int32) >>> x array([[1, 9, 3], [4, 5, 6]], dtype=int32)

### 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 (shape[, dtype, buffer, offset, . ])

An array object represents a multidimensional, homogeneous array of fixed-size items.

### Indexing arrays#

Arrays can be indexed using an extended Python slicing syntax, array[selection] . Similar syntax is also used for accessing fields in a structured data type .

### 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, or by some other object), combined with an indexing scheme that maps *N* integers into the location of an item in the block. The ranges in which the indices can vary is specified by the shape of the array. How many bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.

A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of an *N*-dimensional array in a 1-dimensional block. NumPy is flexible, and ndarray objects can accommodate any *strided indexing scheme*. In a strided scheme, the N-dimensional index \((n_0, n_1, . n_)\) corresponds to the offset (in bytes):

\[n_<\mathrm

from the beginning of the memory block associated with the array. Here, \(s_k\) are integers which specify the strides of the array. The column-major order (used, for example, in the Fortran language and in *Matlab*) and row-major order (used in C) schemes are just specific kinds of strided scheme, and correspond to memory that can be *addressed* by the strides:

\[s_k^<\mathrm

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.

*Contiguous arrays* and *single-segment arrays* are synonymous and are used interchangeably throughout the documentation.

While a C-style and Fortran-style contiguous array, which has the corresponding flags set, can be addressed with the above strides, the actual strides may be different. This can happen in two cases:

- If self.shape[k] == 1 then for any legal index index[k] == 0 . This means that in the formula for the offset \(n_k = 0\) and thus \(s_k n_k = 0\) and the value of \(s_k\)
*= self.strides[k]*is arbitrary. - If an array has no elements ( self.size == 0 ) there is no legal index and the strides are never used. Any array with no elements may be considered C-style and Fortran-style contiguous.

Point 1. means that self and self.squeeze() always have the same contiguity and aligned flags value. This also means that even a high dimensional array could be C-style and Fortran-style contiguous at the same time.

An array is considered aligned if the memory offsets for all elements and the base offset itself is a multiple of *self.itemsize*. Understanding *memory-alignment* leads to better performance on most hardware.

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.

NPY_RELAXED_STRIDES_DEBUG=1 can be used to help find errors when incorrectly relying on the strides in C-extension code (see below warning).

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.

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#

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.

#### Memory layout#

The following attributes contain information about the memory layout of the array:

Information about the memory layout of the array.

Tuple of array dimensions.

Tuple of bytes to step in each dimension when traversing an array.

Number of array dimensions.

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

Number of elements in the array.

Length of one array element in bytes.

Total bytes consumed by the elements of the array.

Base object if memory is from some other object.

#### Data type#

The data type object associated with the array can be found in the dtype attribute:

Data-type of the array’s elements.

#### Other attributes#

View of the transposed array.

The real part of the array.

The imaginary part of the array.

A 1-D iterator over the array.

#### Array interface#

Python-side of the array interface

C-side of the array interface

#### ctypes foreign function interface#

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

### Array methods#

An ndarray object has many methods which operate on or with the array in some fashion, typically returning an array result. These methods are briefly explained below. (Each method’s docstring has a more complete description.)

#### Array conversion#

Copy an element of an array to a standard Python scalar and return it.

Return the array as an a.ndim -levels deep nested list of Python scalars.

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

A compatibility alias for *tobytes*, with exactly the same behavior.

Construct Python bytes containing the raw data bytes in the array.

Write array to a file as text or binary (default).

Dump a pickle of the array to the specified file.

Returns the pickle of the array as a string.

Copy of the array, cast to a specified type.

Swap the bytes of the array elements

Return a copy of the array.

New view of array with the same data.

Returns a field of the given array as a certain type.

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

Fill the array with a scalar value.

#### Shape manipulation#

For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple.

Returns an array containing the same data with a new shape.

Change shape and size of array in-place.

Returns a view of the array with axes transposed.

Return a view of the array with *axis1* and *axis2* interchanged.

Return a copy of the array collapsed into one dimension.

Return a flattened array.

Remove axes of length one from *a*.

#### Item selection and manipulation#

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.

Return an array formed from the elements of *a* at the given indices.

Set a.flat[n] = values[n] for all *n* in indices.

Repeat elements of an array.

Use an index array to construct a new array from a set of choices.

Sort an array in-place.

Returns the indices that would sort this array.

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

Returns the indices that would partition this array.

Find indices where elements of v should be inserted in a to maintain order.

Return the indices of the elements that are non-zero.

Return selected slices of this array along given axis.

Return specified diagonals.

#### Calculation#

Many of these methods take an argument named *axis*. In such cases,

- If
*axis*is*None*(the default), the array is treated as a 1-D array and the operation is performed over the entire array. This behavior is also the default if self is a 0-dimensional array or array scalar. (An array scalar is an instance of the types/classes float32, float64, etc., whereas a 0-dimensional array is an ndarray instance containing precisely one array scalar.) - If
*axis*is an integer, then the operation is done over the given axis (for each 1-D subarray that can be created along the given axis).

Example of the *axis* argument

A 3-dimensional array of size 3 x 3 x 3, summed over each of its three axes

>>> x = np.arange(27).reshape((3,3,3)) >>> x array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) >>> x.sum(axis=0) array([[27, 30, 33], [36, 39, 42], [45, 48, 51]]) >>> # for sum, axis is the first keyword, so we may omit it, >>> # specifying only its value >>> x.sum(0), x.sum(1), x.sum(2) (array([[27, 30, 33], [36, 39, 42], [45, 48, 51]]), array([[ 9, 12, 15], [36, 39, 42], [63, 66, 69]]), array([[ 3, 12, 21], [30, 39, 48], [57, 66, 75]]))

The parameter *dtype* specifies the data type over which a reduction operation (like summing) should take place. The default reduce data type is the same as the data type of *self*. To avoid overflow, it can be useful to perform the reduction using a larger data type.

For several methods, an optional *out* argument can also be provided and the result will be placed into the output array given. The *out* argument must be an ndarray and have the same number of elements. It can have a different data type in which case casting will be performed.

ndarray.max ([axis, out, keepdims, initial, . ])

Return the maximum along a given axis.

Return indices of the maximum values along the given axis.

ndarray.min ([axis, out, keepdims, initial, . ])

Return the minimum along a given axis.

Return indices of the minimum values along the given axis.

Peak to peak (maximum — minimum) value along a given axis.

Return an array whose values are limited to [min, max] .

Complex-conjugate all elements.

Return *a* with each element rounded to the given number of decimals.

ndarray.trace ([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

Return the sum of the array elements over the given axis.

Return the cumulative sum of the elements along the given axis.

ndarray.mean ([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

Returns the variance of the array elements, along given axis.

Returns the standard deviation of the array elements along given axis.

Return the product of the array elements over the given axis

Return the cumulative product of the elements along the given axis.

ndarray.all ([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

ndarray.any ([axis, out, keepdims, where])

Returns True if any of the elements of *a* evaluate to True.

### Arithmetic, matrix multiplication, and comparison operations#

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 .

## 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 methods and attributes of an array.

Parameters : **(for the __new__ method; see Notes below)** **shape** tuple of ints

Shape of created array.

**dtype** data-type, optional

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** , optional

Row-major (C-style) or column-major (Fortran-style) order.

Construct an array.

Create an array, each element of which is zero.

Create an array, but leave its allocated memory unchanged (i.e., it contains “garbage”).

Create a data-type.

An ndarray alias generic w.r.t. its dtype.type .

There are two modes of creating an array using __new__ :

- If
*buffer*is None, then only shape , dtype , and*order*are used. - 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.

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([[0.0e+000, 0.0e+000], # random [ nan, 2.5e-323]])

>>> 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 : T ndarray

View of the transposed array.

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.

all ([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

any ([axis, out, keepdims, where])

Returns True if any of the elements of *a* evaluate to True.

argmax ([axis, out, keepdims])

Return indices of the maximum values along the given axis.

argmin ([axis, out, keepdims])

Return indices of the minimum values along the given axis.

Returns the indices that would partition this array.

Returns the indices that would sort this array.

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

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 [min, 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.

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)

max ([axis, out, keepdims, initial, where])

Return the maximum along a given axis.

mean ([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

min ([axis, out, keepdims, initial, where])

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 the value of the element in kth position is in the position it would be in a sorted array.

prod ([axis, dtype, out, keepdims, initial, . ])

Return the product of the array elements over the given axis

ptp ([axis, out, keepdims])

Peak to peak (maximum — minimum) value along a given axis.

put (indices, values[, mode])

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, WRITEBACKIFCOPY, respectively.

sort ([axis, kind, order])

Sort an array in-place.

Remove axes of length one from *a*.

std ([axis, dtype, out, ddof, keepdims, where])

Returns the standard deviation of the array elements along given axis.

sum ([axis, dtype, out, keepdims, initial, where])

Return the sum of the array elements over the given axis.

Return a view of the array with *axis1* and *axis2* interchanged.

take (indices[, axis, out, mode])

Return an array formed from the elements of *a* at the given indices.

Construct Python bytes containing the raw data bytes in the array.

Write array to a file as text or binary (default).

Return the array as an a.ndim -levels deep nested list of Python scalars.

A compatibility alias for tobytes , with exactly the same behavior.

trace ([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

Returns a view of the array with axes transposed.

var ([axis, dtype, out, ddof, keepdims, where])

Returns the variance of the array elements, along given axis.

New view of array with the same data.

**dot**

The N-dimensional array ( ndarray )

## 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* non-negative integers that specify the sizes of each dimension. The type of items in the array is specified by a separate data-type object (dtype) , one of which is associated with each ndarray.

As with other container objects in Python, the contents of an ndarray can be accessed and modified by indexing or slicing the array (using, for example, *N* integers), and via the methods and attributes of the ndarray .

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

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) >>> x.shape (2, 3) >>> x.dtype dtype('int32')

The array can be indexed using Python container-like syntax:

>>> # The element of x in the *second* row, *third* column, namely, 6. >>> x[1, 2] 6

For example slicing can produce views of the array:

>>> y = x[:,1] >>> y array([2, 5], dtype=int32) >>> y[0] = 9 # this also changes the corresponding element in x >>> y array([9, 5], dtype=int32) >>> x array([[1, 9, 3], [4, 5, 6]], dtype=int32)

### 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 (shape[, dtype, buffer, offset, . ])

An array object represents a multidimensional, homogeneous array of fixed-size items.

### Indexing arrays#

Arrays can be indexed using an extended Python slicing syntax, array[selection] . Similar syntax is also used for accessing fields in a structured data type .

### 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, or by some other object), combined with an indexing scheme that maps *N* integers into the location of an item in the block. The ranges in which the indices can vary is specified by the shape of the array. How many bytes each item takes and how the bytes are interpreted is defined by the data-type object associated with the array.

A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of an *N*-dimensional array in a 1-dimensional block. NumPy is flexible, and ndarray objects can accommodate any *strided indexing scheme*. In a strided scheme, the N-dimensional index \((n_0, n_1, . n_)\) corresponds to the offset (in bytes):

\[n_<\mathrm

from the beginning of the memory block associated with the array. Here, \(s_k\) are integers which specify the strides of the array. The column-major order (used, for example, in the Fortran language and in *Matlab*) and row-major order (used in C) schemes are just specific kinds of strided scheme, and correspond to memory that can be *addressed* by the strides:

\[s_k^<\mathrm

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.

*Contiguous arrays* and *single-segment arrays* are synonymous and are used interchangeably throughout the documentation.

While a C-style and Fortran-style contiguous array, which has the corresponding flags set, can be addressed with the above strides, the actual strides may be different. This can happen in two cases:

- If self.shape[k] == 1 then for any legal index index[k] == 0 . This means that in the formula for the offset \(n_k = 0\) and thus \(s_k n_k = 0\) and the value of \(s_k\)
*= self.strides[k]*is arbitrary. - If an array has no elements ( self.size == 0 ) there is no legal index and the strides are never used. Any array with no elements may be considered C-style and Fortran-style contiguous.

Point 1. means that self and self.squeeze() always have the same contiguity and aligned flags value. This also means that even a high dimensional array could be C-style and Fortran-style contiguous at the same time.

An array is considered aligned if the memory offsets for all elements and the base offset itself is a multiple of *self.itemsize*. Understanding *memory-alignment* leads to better performance on most hardware.

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.

NPY_RELAXED_STRIDES_DEBUG=1 can be used to help find errors when incorrectly relying on the strides in C-extension code (see below warning).

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.

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#

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.

#### Memory layout#

The following attributes contain information about the memory layout of the array:

Information about the memory layout of the array.

Tuple of array dimensions.

Tuple of bytes to step in each dimension when traversing an array.

Number of array dimensions.

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

Number of elements in the array.

Length of one array element in bytes.

Total bytes consumed by the elements of the array.

Base object if memory is from some other object.

#### Data type#

The data type object associated with the array can be found in the dtype attribute:

Data-type of the array’s elements.

#### Other attributes#

View of the transposed array.

The real part of the array.

The imaginary part of the array.

A 1-D iterator over the array.

#### Array interface#

Python-side of the array interface

C-side of the array interface

#### ctypes foreign function interface#

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

### Array methods#

An ndarray object has many methods which operate on or with the array in some fashion, typically returning an array result. These methods are briefly explained below. (Each method’s docstring has a more complete description.)

#### Array conversion#

Copy an element of an array to a standard Python scalar and return it.

Return the array as an a.ndim -levels deep nested list of Python scalars.

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

A compatibility alias for *tobytes*, with exactly the same behavior.

Construct Python bytes containing the raw data bytes in the array.

Write array to a file as text or binary (default).

Dump a pickle of the array to the specified file.

Returns the pickle of the array as a string.

Copy of the array, cast to a specified type.

Swap the bytes of the array elements

Return a copy of the array.

New view of array with the same data.

Returns a field of the given array as a certain type.

Set array flags WRITEABLE, ALIGNED, WRITEBACKIFCOPY, respectively.

Fill the array with a scalar value.

#### Shape manipulation#

For reshape, resize, and transpose, the single tuple argument may be replaced with n integers which will be interpreted as an n-tuple.

Returns an array containing the same data with a new shape.

Change shape and size of array in-place.

Returns a view of the array with axes transposed.

Return a view of the array with *axis1* and *axis2* interchanged.

Return a copy of the array collapsed into one dimension.

Return a flattened array.

Remove axes of length one from *a*.

#### Item selection and manipulation#

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.

Return an array formed from the elements of *a* at the given indices.

Set a.flat[n] = values[n] for all *n* in indices.

Repeat elements of an array.

Use an index array to construct a new array from a set of choices.

Sort an array in-place.

Returns the indices that would sort this array.

Rearranges the elements in the array in such a way that the value of the element in kth position is in the position it would be in a sorted array.

Returns the indices that would partition this array.

Find indices where elements of v should be inserted in a to maintain order.

Return the indices of the elements that are non-zero.

Return selected slices of this array along given axis.

Return specified diagonals.

#### Calculation#

Many of these methods take an argument named *axis*. In such cases,

- If
*axis*is*None*(the default), the array is treated as a 1-D array and the operation is performed over the entire array. This behavior is also the default if self is a 0-dimensional array or array scalar. (An array scalar is an instance of the types/classes float32, float64, etc., whereas a 0-dimensional array is an ndarray instance containing precisely one array scalar.) - If
*axis*is an integer, then the operation is done over the given axis (for each 1-D subarray that can be created along the given axis).

Example of the *axis* argument

A 3-dimensional array of size 3 x 3 x 3, summed over each of its three axes

>>> x = np.arange(27).reshape((3,3,3)) >>> x array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) >>> x.sum(axis=0) array([[27, 30, 33], [36, 39, 42], [45, 48, 51]]) >>> # for sum, axis is the first keyword, so we may omit it, >>> # specifying only its value >>> x.sum(0), x.sum(1), x.sum(2) (array([[27, 30, 33], [36, 39, 42], [45, 48, 51]]), array([[ 9, 12, 15], [36, 39, 42], [63, 66, 69]]), array([[ 3, 12, 21], [30, 39, 48], [57, 66, 75]]))

The parameter *dtype* specifies the data type over which a reduction operation (like summing) should take place. The default reduce data type is the same as the data type of *self*. To avoid overflow, it can be useful to perform the reduction using a larger data type.

For several methods, an optional *out* argument can also be provided and the result will be placed into the output array given. The *out* argument must be an ndarray and have the same number of elements. It can have a different data type in which case casting will be performed.

ndarray.max ([axis, out, keepdims, initial, . ])

Return the maximum along a given axis.

Return indices of the maximum values along the given axis.

ndarray.min ([axis, out, keepdims, initial, . ])

Return the minimum along a given axis.

Return indices of the minimum values along the given axis.

Peak to peak (maximum — minimum) value along a given axis.

Return an array whose values are limited to [min, max] .

Complex-conjugate all elements.

Return *a* with each element rounded to the given number of decimals.

ndarray.trace ([offset, axis1, axis2, dtype, out])

Return the sum along diagonals of the array.

Return the sum of the array elements over the given axis.

Return the cumulative sum of the elements along the given axis.

ndarray.mean ([axis, dtype, out, keepdims, where])

Returns the average of the array elements along given axis.

Returns the variance of the array elements, along given axis.

Returns the standard deviation of the array elements along given axis.

Return the product of the array elements over the given axis

Return the cumulative product of the elements along the given axis.

ndarray.all ([axis, out, keepdims, where])

Returns True if all elements evaluate to True.

ndarray.any ([axis, out, keepdims, where])

Returns True if any of the elements of *a* evaluate to True.

### Arithmetic, matrix multiplication, and comparison operations#

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 .