2. The NDArray Object
The ndarray Memory Structure
At the core of NumPy lies the ndarray, a powerful n-dimensional array object. Unlike standard Python lists, which store pointers to objects scattered in memory, an ndarray stores data in a contiguous block of memory.
This contiguous structure ensures that elements are laid out sequentially. This design is crucial for CPU cache efficiency, as modern processors can load blocks of data into cache much faster than fetching disparate pointers.
import numpy as np arr = np.array([1, 2, 3, 4], dtype='int32') print(f'Memory address of start: {arr.ctypes.data}') print(f'Is contiguous? {arr.flags["C_CONTIGUOUS"]}')
Understanding Strides and Stride Mechanics
Strides are the number of bytes required to step over each dimension of an array. If you have a 2D array, the stride tells NumPy how many bytes to jump to get to the next element in the same row versus the next element in the next row.
This mechanism allows NumPy to perform complex operations like transposition or slicing without actually moving data in memory. Instead, it simply updates the strides and offsets.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]], dtype='int32') print(f'Strides: {arr.strides}')
Data Types (dtypes): Casting and Overflow
NumPy dtypes allow for precise control over memory. Using smaller types like int8 saves memory but introduces the risk of overflow—where a calculation exceeds the maximum representable value.
You can explicitly cast arrays using the .astype() method. This creates a new array with the requested data type.
import numpy as np arr = np.array([127], dtype='int8') print(f'Overflow result: {arr + 1}') casted = arr.astype('float64') print(f'New dtype: {casted.dtype}')
Array Attributes
NumPy arrays provide metadata through attributes. These properties define the structure of the data.
| Attribute | Description |
|---|---|
| shape | Tuple representing dimensions. |
| ndim | Number of dimensions (axes). |
| itemsize | Bytes per element. |
| nbytes | Total memory used. |
import numpy as np arr = np.zeros((3, 4), dtype='int32') print(f'Shape: {arr.shape}, Dimensions: {arr.ndim}') print(f'Bytes per item: {arr.itemsize}, Total bytes: {arr.nbytes}')
Knowledge Check
Ready to test your understanding of 2. The NDArray Object?