Python:NumPy ndarray
An ndarray is a NumPy data structure that stores elements of the same data type in a multi-dimensional array. The number of dimensions and items contained in the array is defined with a tuple of N non-negative integers that specify each dimension’s size. An ndarray has an associated data-type object which specifies the dtype (datatype) stored in the ndarray.
An ndarray is like other container objects in Python, like lists and tuples, but with its unique features. The items in an ndarray can be accessed by indexing and slicing the array. There are also a number of methods and attributes of the ndarray that can be used to access and manipulate its contents.
Separate instances of an ndarray can share contents so that changes in one ndarray can be reflected in another. This happens when an ndarray is created as a “view” of another ndarray known as the “base”.
Creating an ndarray
There are several routines for creating ndarray objects. These are preferred to using the ndarray constructor, which operates at a very low level. Here are a few examples:
| Method | Syntax | Description |
|---|---|---|
.empty() |
numpy.empty(shape,dtype) |
Creates a ndarray of the given shape tuple, and the optional dtype (default is numpy.float64) with uninitialized values. |
.empty_like() |
numpy.empty_like(model,dtype) |
Creates a ndarray based on the shape of the model, with the optional dtype (default is data type of model) with uninitialized values. |
.ones() |
numpy.ones(shape,dtype) |
Operates the same as .empty(), but initializes all the array elements with a value of one. |
.ones_like() |
numpy.ones_like(model,dtype) |
Operates the same as .empty_like(), but initializes all the array elements with a value of one. |
.zeros() |
numpy.zeros(shape,dtype) |
Operates the same as .empty(), but initializes all the array elements with a value of zero. |
.zeros_like() |
numpy.zeros_like(model,dtype) |
Operates the same as .empty_like(), but initializes all the array elements with a value of zero. |
.full() |
numpy.full(shape,value,dtype) |
Operates the same as .empty(), but initializes all the array elements with the specified value. |
.full_like() |
numpy.full_like(model,value,dtype) |
Operates the same as .empty_like(), but initializes all the array elements with the specified value. |
.array() |
numpy.array(object,dtype) |
Creates an ndarray based on the given object (such as a list of lists) with the optional dtype. If not specified, the data type will be based on the contents of object. |
Example
The following shows various methods of creating an ndarray.
import numpy as npnd1 = np.array([[1,2,3],[4,5,6],[7,8,9]])nd2 = np.ones_like(nd1)nd3 = np.full((2,2),5)print(nd1)print(nd2)print(nd3)
This produces the following output:
[[1 2 3][4 5 6][7 8 9]][[1 1 1][1 1 1][1 1 1]][[5 5][5 5]]
Operations on an ndarray
The standard mathematical operations, when applied to ndarrays are evaluated internally as equivalent universal functions (“ufuncs”). Universal functions (“ufuncs”) are functions that operate on ndarrays on an element-by-element basis. There are over 60 universal functions in total and there are even ufuncs for each mathematical operation. Some of the most popular operations are summarized below:
| Operator | Ufunc | Description |
|---|---|---|
+ |
numpy.add(X,Y) |
Adds arguments, element-wise. |
- |
numpy.subtract(X,Y) |
Subtracts arguments, element-wise. |
* |
numpy.multiply(X,Y) |
Multiplies arguments, element-wise. |
/ |
numpy.divide(X,Y) |
Division of arguments, element-wise. |
** |
numpy.power(X,Y) |
First array raised to powers of second array, element-wise. |
% |
numpy.mod(X,Y) |
Integer remainder of division, element-wise. |
// |
numpy.floor_divide(X,Y) |
Integer result of division, rounded down, element-wise. |
@ |
numpy.matmul(X,Y) |
Matrix multiplication of arguments. (The @ operator was introduced in Python 3.5) |
Example
The following example creates an ndarray and performs several operations on it.
import numpy as npnd1 = np.array([[1,2,3],[4,5,6],[7,8,9]])print(nd1)print(nd1 + 5)print(nd1 % 2)print(np.matmul(nd1, nd1 % 2))
This produces the following output:
[[1 2 3][4 5 6][7 8 9]][[ 6 7 8][ 9 10 11][12 13 14]][[1 0 1][0 1 0][1 0 1]][[ 4 2 4][10 5 10][16 8 16]]
ndarray
- .all()
- Returns True if all elements in the array evaluate to True, or along a specified axis.
- .argmax()
- Returns the indices of the maximum values along a specified axis.
- .astype()
- Converts a NumPy array to a specified data type.
- .clip()
- Limits the values in an array to a specified range.
- .copy()
- Creates and returns a new, independent copy of a NumPy ndarray.
- .cumprod()
- Returns the cumulative product of array elements along a specified axis.
- .cumsum()
- Computes the cumulative sum of array elements along a specified axis.
- .diagonal()
- Returns the specified diagonal elements of an array.
- .dot()
- Computes the dot product of two arrays.
- .fill()
- Fills a NumPy array with a specified scalar value.
- .flatten()
- Returns a copy of an array collapsed into one dimension.
- .item()
- Copies an element of a NumPy ndarray to a standard Python scalar and returns it.
- .itemsize
- Returns the size in bytes of each element in a NumPy array.
- .nbytes
- Returns the total number of bytes consumed by the elements of the array.
- .nonzero()
- Returns the indices of the array elements that are non-zero.
- .prod()
- Calculates the product of all elements in a NumPy array, optionally along a specified axis.
- .ravel()
- Returns a contiguous flattened array.
- .repeat()
- Returns the repeated elements of an array.
- .reshape()
- Rearranges the data of an ndarray into a new shape.
- .resize()
- Changes the shape of a NumPy array in-place.
- .searchsorted()
- Returns the index where a value should be inserted to maintain order.
- .shape
- Returns a tuple representing the dimensions of an ndarray.
- .sort()
- Sorts the array in-place along the specified axis.
- .squeeze()
- Removes dimensions of size 1 from an ndarray.
- .sum()
- Returns the sum of array elements over a given axis.
- .swapaxes()
- Returns a view of the array with two axes interchanged.
- .tolist()
- Converts an array into a nested list of Python scalars.
- .trace()
- Returns the sum of the elements along the diagonal of an array.
- .transpose()
- Returns a view of the array with axes permuted.
- .view()
- Returns a new view of the array's data without copying the underlying memory.
- any()
- Returns True if any element of the array evaluates to True, otherwise it returns False.
- argmin()
- Returns the index of the minimum value in a NumPy array or along a specified axis.
- byteswap()
- Swaps the byte order of each element in a NumPy ndarray.
- flat
- Returns a 1-D iterator over the elements of an ndarray.
- mean()
- Computes the arithmetic mean of array elements along a given axis.
- min()
- Returns the minimum value in a NumPy array or along a specified axis.
- ndim
- Returns the number of dimensions (axes) of a NumPy array.
- round()
- Returns a new array with each element rounded to the specified number of decimals.
- size
- Returns the number of elements in a NumPy array.
- take()
- Returns elements from an array at specific indices.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours