NumPy ndarray

NoteQuestion

What is a NumPy ndarray?

TipAnswer

Put simply, an ndarray is a data container, like dictionaries and lists.

NoteQuestion

Can ndarrays contain objects of different type?

TipAnswer

No, they cannot. An ndarray must contain homogenous items; that is, items of the same type.

NoteQuestion

How do I create an ndarray?

TipAnswer

As shown in the code snippet below, we pass an object to numpy.array. If the object we pass is a scalar, a 0-dimensional array containing object is returned (line 5). Passing a list to numpy.array produces a one-dimensional array (line 9); passing a list of lists produces a two-dimensional array (line 13); finally, passing a list of lists of lists produces a three-dimensional array (line 18).

# import numpy with the socially accepted alias 'np'
>>> import numpy as np

# a 0-D array
>>> np.array(0)
array(0)

# a 1-D array
>>> np.array([1, 2, 3, 4])
array([1, 2, 3, 4])

# a 2-D array
>>> np.array([[1, 2], [3, 4]])
array([[1, 2],
       [3, 4]])

# a 3-D array
>>> np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array([[[1, 2],
        [3, 4]],

       [[5, 6],
        [7, 8]]])
NoteQuestion

What are the distinctive features of ndarrays?

TipAnswer

ndarrays have been designed — and tuned over time — with flexibility and efficiency in mind. For example, ndarrays allows to carry out computations on arrays with a syntax similar to scalar values. As shown in the code snippet below, we can multiply an array by a scalar (line 10) and add two vectors (14). That is not possible if we use pure Python code. Multiplying a list by a scalar N replicates the ordered collection of items N times (see line 23). Adding two lists yields concatenation (see line 30). At the same time, ndarrays support the analysis of large volumes of data. The Internet has many blog posts showing the performance of NumPy in linear algebra tasks is comparable to compiled languages, such as C.

# import numpy with the socially accepted alias 'np'
import numpy as np

# generate some random
>>> DATA = np.random.randn(3)
>>> print(DATA)
[-0.44144029 -0.44451097  0.31997294]

# can we multiply a list by a scalar with NumPy? Of course!
>>> print(DATA * 3)
[-4.4144029 , -4.44510974,  3.19972941]

# can we sum two arrays with NumPy? Of course!
>>> print(DATA + DATA)
[-0.88288058, -0.88902195,  0.63994588]

# let us try to replicate the previous tasks in pure Python?
# --+ get the DATA as a list
>>> DATA = list(DATA)
>>> print(DATA)
[-0.4414402896845323, -0.4445109735283278, 0.31997294069261617]
# --+ is the NumPy syntax of line 10 still valid if we use a list? Nope
>>> print(DATA * 3)
[
-0.4414402896845323, -0.4445109735283278, 0.31997294069261617,
-0.4414402896845323, -0.4445109735283278, 0.31997294069261617,
-0.4414402896845323, -0.4445109735283278, 0.31997294069261617
]
# --+ is the NumPy syntax of line 14 still valid if we use a list? Nope
>>> print(DATA + DATA)
[
-0.4414402896845323, -0.4445109735283278, 0.31997294069261617,
-0.4414402896845323, -0.4445109735283278, 0.31997294069261617
]
NoteQuestion

How do I check an array’s number of dimensions?

TipAnswer

NumPy infers an ndarrays’s number of dimensions from the data. The code snippet below shows how to access .ndim, the ndarrays’s attribute concerning the number of dimensions. In the example, DATA has two dimensions (e.g., coordinates).

NoteQuestion

How do I check an array’s shape?

TipAnswer

The lower section of the code snippet below shows how to access .shape, the ndarrays’s attribute concerning the shape. In the example, each dimension of the DATA has size 2.

# import numpy with the socially accepted alias 'np'
>>> import numpy as np

# the data
>>> DATA = np.array([[1, 2], [3, 4]])
>>> print(DATA)
[[1 2]
 [3 4]]

# get the number of dimensions
>>> DATA.ndim
2

# get the shape
>>> DATA.shape
(2, 2)
NoteQuestion

What are the attributes of an array?

TipAnswer

The table below illustrates the common use attributes of ndarrays.

Attribute Synopsis
DATA.flags Information about the memory layout of the array
DATA.shape Tuple of array dimensions
DATA.strides Tuple of bytes to step in each dimension when traversing an array
DATA.ndim Number of array dimensions
DATA.data Python buffer object pointing to the start of the array’s data
DATA.size Number of elements in the array
DATA.itemsize Length of one array element in bytes
DATA.nbytes Total bytes consumed by the elements of the array
DATA.dtype Data-type of the array’s elements

Note: DATA is a fictionary object used to illustrate the usage of the array attributes.

NoteQuestion

I know that a NumPy array must contain homogenous data — but which object types are allowed?

TipAnswer

The table below reports the NumPy data types. Python beginners are not supposed to appreciate the distinctive attributes of each type. Instead, they may want to get a clear understanding of the high-level types, namely, floating points, complex, integer, boolean, string, or general Python objects. When working on sophisticated projects requiring more control over the storage types, it is highly suggested to get a thorough knowledge of the types in the table below. It is worth noticing that dtypes are a source of NumPy’s flexibility for interacting with data coming from other systems. In most cases, they map directly onto an underlying disk or memory representation, making it easy to read and write binary data streams to disk and connect to code written in a low-level language like C or Fortran. The numerical dtypes are named the same way: a type name, like float or int, followed by a number indicating the number of bits per element. A standard double-precision floating-point value takes up 8 bytes or 64 bits. Thus, this type is known in NumPy as float64.

Type Type Code Synopsis
int8, uint8 i1, u1 Signed and unsigned 8-bit (1 byte) integer types
int16, uint16 i2, u2 Signed and unsigned 16-bit integer types
int32, uint32 i4, u4 Signed and unsigned 32-bit integer types
int64, uint64 i8, u8 Signed and unsigned 64-bit integer types
float16 f2 Half-precision floating point float32 f4 or f Standard single-precision floating-point; compatible with C float
float64 f8 or d Standard double-precision floating-point; compatible with C double and Python
float object float128 f16 or g Extended-precision floating point
complex64, complex128, complex256 c8, c16, c32 Complex numbers represented by two 32, 64, or 128 floats, respectively
bool ? Boolean type storing True and False values
object O Python object type; a value can be any Python object
bytes_ (was string_) S Fixed-length ASCII string type (1 byte per character); for example, to create a string dtype with length 10, use ‘S10’
str_ (was unicode_) U Fixed-length Unicode type (number of bytes platform specific); same specification semantics as bytes_ (e.g., ‘U10’)
NoteQuestion

How do I specify the data type of an array?

TipAnswer

As the code snippet below shows, dtype is an optional argument of ndarray. It is also possible to change dtype using the method .astype().

# import numpy with the socially accepted alias 'np'
>>> import numpy as np

# accept the default type
>>> A = np.array([1, 2, 3, 4, 5])

# check the type
>>> A.dtype
dtype('int64')

# specify the type
>>> A = np.array([1, 2, 3, 4, 5], dtype=np.int32)

# check the type
>>> A.dtype
dtype('int32')

# type change
>>> S = np.array(['1.25', '-9.6', '42'], dtype="S")
>>> S = S.astype(float)
>>> S.dtype
dtype('float64')