30 Mins

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.

Operator Note: Always prioritize contiguous arrays for performance-heavy numerical computing.
Python 3
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.

Operator Note: Negative strides are used internally when you slice an array in reverse, e.g., arr[::-1].
Python 3
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.

Operator Note: Always check your data ranges before using fixed-size integers like int8 or uint16.
Python 3
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.

AttributeDescription
shapeTuple representing dimensions.
ndimNumber of dimensions (axes).
itemsizeBytes per element.
nbytesTotal memory used.
Operator Note: Use nbytes to monitor memory usage when working with massive datasets.
Python 3
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?

Back