Arrays & NumPy Array Processing
An authoritative reference manual on native Python array module vs NumPy ndarrays, C-contiguous memory layouts, strides, SIMD vectorization, aliasing vs view vs copy, basic slicing, advanced fancy indexing, boolean masks, and attributes.
Array processing forms the foundation of high-performance numerical computing. This chapter contrasts native Python arrays against multidimensional NumPy arrays, detailing SIMD vectorization, memory strides, aliasing, basic slicing, advanced fancy indexing, boolean masking, and array attributes.
4.1. 1. Native Python Array Module vs NumPy Arrays
Definition: The native `array` module manages 1D homogeneous primitive values; `NumPy` provides N-dimensional C-contiguous array structures (`ndarray`) optimized for vectorized SIMD math operations.
Core Working Principles:
- Native Array Module: `import array; array.array('i', [1, 2, 3])`. Stores homogenous C primitives in contiguous memory, restricted to 1D.
- NumPy `ndarray` Architecture: Multidimensional C-contiguous or Fortran-contiguous memory buffer. Uses **Strides** (byte steps required to step to the next element in each dimension). Executes SIMD (Single Instruction Multiple Data) CPU vectorization without Python `for` loops.
- Memory Allocation Paradigms:
- • Aliasing (`b = a`): Creates a new variable reference pointing to the exact same array memory address.
- • Shallow Copy / View (`b = a.view()` / slicing): Creates a new array object sharing underlying data memory.
- • Deep Copy (`b = a.copy()`): Allocates a brand-new independent memory buffer.
| Feature Dimension | Python Lists | Native array Module |
NumPy ndarray 🏆 |
|---|---|---|---|
| Data Homogeneity | Heterogeneous (mixed data types) | Homogeneous (single primitive type) | Homogeneous (single data type) |
| Dimensionality | 1D (Nested lists for multi-D) | 1D only | Arbitrary N-Dimensions |
| Math Execution | Python loops (Slow $O(N)$ overhead) | Python loops (Moderate) | Vectorized C-speed SIMD broadcasting |
5-Marks Exam Scoring Points
- NumPy ndarrays execute math at C speed via SIMD vectorization.
- b = a creates an alias pointer; b = a.copy() creates a deep memory copy.
- Native array module is limited to 1D primitive values.
4.2. 2. NumPy Slicing, Advanced Indexing & Attributes
Definition: NumPy arrays support basic slicing, advanced integer/boolean indexing, and multidimensional shape manipulation.
Core Working Principles:
- Array Attributes: `ndim` (number of dimensions), `shape` (tuple of dimensions), `size` (total elements), `dtype` (element data type), `strides` (byte steps per axis).
- Basic Slicing: `arr[r_start:r_stop, c_start:c_stop]`. Returns a memory **View**.
- Advanced Indexing:
- • Fancy Integer Indexing: `arr[[0, 2]]` selects specific non-contiguous rows. Returns a **Copy**.
- • Boolean Mask Indexing: `arr[arr > 5]` filters elements matching a Boolean condition. Returns a **Copy**.
graph TD
Arr[2D NumPy Array Shape 3x3] --> Attr[Attributes: ndim=2, shape=3,3, size=9]
Arr --> BasicSlice[Basic Slicing: arr 0:2, 1:3 -> Returns View]
Arr --> FancyIndex[Fancy Indexing: arr 0, 2 -> Returns Copy]
Arr --> BoolIndex[Boolean Indexing: arr arr > 50 -> Returns 1D Filtered Copy]
import numpy as np
# Create 2D NumPy Array
matrix = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Attributes
print(f"Dimensions: {matrix.ndim} | Shape: {matrix.shape} | Size: {matrix.size} | Dtype: {matrix.dtype}")
# 1. Basic Slicing (Rows 0-1, Cols 1-2) -> Returns View
view_slice = matrix[0:2, 1:3]
# 2. Fancy Integer Indexing (Select Rows 0 and 2) -> Returns Copy
row_copy = matrix[[0, 2]]
# 3. Boolean Mask Indexing (Elements > 45) -> Returns Copy
mask_copy = matrix[matrix > 45]
print("Boolean Filtered Result (>45):", mask_copy)
5-Marks Exam Scoring Points
- Basic slicing returns a View; modifying values in a view mutates the original array.
- Advanced indexing (integer array / boolean mask) allocates a brand-new Copy.
- Array shape can be reshaped using reshape(rows, cols).
✍️ Chapter 4 Reference Exercises & Review Problems
- **Basic Slicing (`arr[0:2, 1:3]`):** Generates a **View** sharing original memory. No new memory buffer is allocated; altering view data directly mutates the source array!
- **Advanced Indexing (`arr[[0, 2]]` or `arr[arr > 5]`):** Generates an independent **Copy** in new memory. Modifying elements in the copied array does NOT affect the source array.
import numpy as np
arr = np.arange(1, 10).reshape(3, 3)
# (a) Middle Row (index 1)
middle_row = arr[1, :] # Output: [4, 5, 6]
# (b) Last Column (index -1)
last_col = arr[:, -1] # Output: [3, 6, 9]
# (c) Elements greater than 5
gt_five = arr[arr > 5] # Output: [6, 7, 8, 9]