NumPy Ndarray Object

NumPy's most important feature is its N-dimensional array object ndarray, which is a collection of data of the same type, with indexing of elements starting at subscript 0.

The ndarray object is a multidimensional array used to store elements of the same type.

Each element in ndarray occupies an area of the same storage size in memory.

ndarray internally consists of the following:

  • A pointer to data (a block of data in memory or a memory-mapped file).

  • A data type or dtype, describing the grid of fixed-size values in the array.

  • A tuple representing the shape of the array, a tuple representing the size of each dimension.

  • A stride tuple, in which the integers refer to the number of bytes that need to be "stepped over" to advance to the next element in the current dimension.

Internal structure of ndarray:

Strides can be negative, which makes the array move backward in memory; in slicing, obj[::-1]orobj[:,::-1]this is exactly the case.

To create an ndarray, simply call NumPy's array function:

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

Parameter description:

Name Description
object Array or nested sequence
dtype Data type of array elements, optional
copy Whether the object needs to be copied, optional
order The style of creating the array: C for row-major, F for column-major, A for any direction (default)
subok By default, returns an array consistent with the base class type
ndmin Specifies the minimum dimension of the generated array

Example

Next, the following examples can help us understand better.

Example 1

import numpy as np a = np.array([1,2,3]) print (a)

The output result is as follows:

[1 2 3]

Example 2

# More than one dimension import numpy as np a = np.array([[1, 2], [3, 4]]) print (a)

The output result is as follows:

[[1  2] 
 [3  4]]

Example 3

# Minimum dimension import numpy as np a = np.array([1, 2, 3, 4, 5], ndmin = 2) print (a)

The output is as follows:

[[1 2 3 4 5]]

Example 4

# dtype parameter import numpy as np a = np.array([1, 2, 3], dtype = complex) print (a)

The output result is as follows:

[1.+0.j 2.+0.j 3.+0.j]

The ndarray object consists of a contiguous one-dimensional segment of computer memory, combined with an indexing pattern that maps each element to a position in the memory block. The memory block stores elements in row order (C style) or column order (FORTRAN or MatLab style, i.e., the aforementioned F style).

Other Extensions