w3resource
NumPy Tutorial

NumPy: N-dimensional array (ndarray)

N-dimensional array

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.

NumPy N-dimensional array axis
The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray.

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

NumPy N-dimensional array

A 2-dimensional array of size 2 x 3, composed of 4-byte integer elements:

Example-1

>>> import numpy as np
>>> a = np.array([[3, 4, 5], [6, 7, 8]], np.int32)

>>> a.shape
(2, 3)
>>> a.dtype
dtype('int32')

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

Example - 2

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

For example slicing can produce views of the array:

Example - 3

>>> import numpy as np
>>> b = a[:,1]
>>> b
array([4, 7])
>>> b[0] = 7
>>> b
array([7, 7])
>>> a
array([[3, 7, 5],
       [6, 7, 8]])

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

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.

 

Previous: NumPy Data Types
Next: NumPy array Home