NumPy Ndarray Object
The most important feature of NumPy is its N-dimensional array object, ndarray, which is a collection of homogeneous data elements indexed starting from 0.
The ndarray object is used to store multidimensional arrays of the same type of elements.
Each element in the ndarray has the same storage size in memory.
The ndarray consists of the following components:
- A pointer to the data (a block of data in memory or a memory-mapped file).
- A data type or dtype, which describes the fixed-size grid of values in the array.
- A tuple representing the array's shape, which indicates the size of each dimension.
- A stride tuple, where the integers indicate the number of bytes to "step over" to move to the next element in the current dimension.
The internal structure of ndarray:
Strides can be negative, which causes the array to move backward in memory. This is how slicing like obj[::-1]
or obj[:,::-1]
works.
Creating an ndarray is as simple as calling the NumPy 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 the array elements, optional |
copy | Whether the object needs to be copied, optional |
order | Style of array creation, C for row-wise, F for column-wise, A for any direction (default) |
subok | By default, returns an array of the same base type |
ndmin | Specifies the minimum dimension of the resulting array |
Example
The following examples will help us better understand.
Example 1
import numpy as np
a = np.array([1,2,3])
print (a)
Output:
[1 2 3]
Example 2
# More than one dimension
import numpy as np
a = np.array([[1, 2], [3, 4]])
print (a)
Output:
[[1 2]
[3 4]]
Example 3
# Minimum dimensions
import numpy as np
a = np.array([1, 2, 3, 4, 5], ndmin = 2)
print (a)
Output:
[[1 2 3 4 5]]
Example 4
# dtype parameter
import numpy as np
a = np.array([1, 2, 3], dtype = complex)
print (a)
Output:
[1.+0.j 2.+0.j 3.+0.j]
The ndarray object is composed of a contiguous one-dimensional segment of computer memory, combined with an indexing scheme 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).