NumPy Basics & N-Dimensional Arrays

Module 5 • Session 33 • Allocation: 1 Contact Hr

numpy ndarray vectorization broadcasting slicing

NumPy (Numerical Python) is the foundational package for scientific computing in Python. It provides high-performance, contiguous-memory $N$-dimensional array objects (ndarray) along with vectorized functions that perform numerical calculations orders of magnitude faster than standard Python lists.

1. The NumPy ndarray Object

An ndarray is a multidimensional array containing elements of a uniform data type. Unlike Python lists containing references to disparate objects, NumPy arrays store raw values sequentially in memory for optimized CPU cache execution.

Array Attribute Type Description / Purpose
arr.shape Tuple of ints Returns the dimensions of the array (e.g., (rows, columns)).
arr.ndim Integer Returns the number of array dimensions (axes count).
arr.dtype NumPy dtype Identifies the data type of the stored elements (e.g., int64, float64).
arr.size Integer Returns the total number of elements present across all axes.

Example 1: Creating Arrays and Checking Attributes

The code below shows how to construct 1D and 2D arrays from standard Python lists and examine their underlying properties:

import numpy as np # 1. Constructing 1D and 2D arrays arr_1d = np.array([10, 20, 30, 40, 50]) arr_2d = np.array([[1.5, 2.5, 3.5], [4.5, 5.5, 6.5]]) print("1D Array Shape:", arr_1d.shape) # Output: (5,) print("2D Array Shape:", arr_2d.shape) # Output: (2, 3) print("2D Array Dimensions:", arr_2d.ndim) # Output: 2 print("Element Data Type:", arr_2d.dtype) # Output: float64 # 2. Built-in array generation helpers zeros_matrix = np.zeros((3, 3)) # 3x3 array filled with 0.0 ones_matrix = np.ones((2, 4)) # 2x4 array filled with 1.0 seq_range = np.arange(0, 10, 2) # Array [0, 2, 4, 6, 8] linear_space = np.linspace(0, 1, 5) # 5 evenly spaced numbers from 0 to 1
Convention Note: Standard Python practice imports the library as import numpy as np across scientific and data science workflows.

2. Array Slicing, Indexing & Boolean Masking

NumPy arrays support multidimensional slicing using comma-separated index ranges: [row_slice, col_slice]. Additionally, logical conditions can be applied directly to extract subsets matching specific criteria via boolean masking.

import numpy as np matrix = np.array([ [10, 20, 30], [40, 50, 60], [70, 80, 90] ]) # Slicing: [rows, columns] sub_matrix = matrix[0:2, 1:3] # Result: [[20, 30], # [50, 60]] # Extracting a specific column col_0 = matrix[:, 0] # Array [10, 40, 70] # Boolean Masking mask = matrix > 45 filtered_vals = matrix[mask] # Array [50, 60, 70, 80, 90]

3. Vectorization and Broadcasting

Vectorization eliminates manual loop constructs by performing calculations across whole arrays at once. Broadcasting allows NumPy to execute arithmetic operations between arrays of differing shapes when their dimensions are compatible.

Broadcasting Compatibility Rule

Two dimensions are compatible for broadcasting if they are equal, or if one of the dimensions is equal to $1$.

import numpy as np # Scalar Broadcasting arr = np.array([1, 2, 3, 4]) scaled = arr * 10 # Results in [10, 20, 30, 40] # Matrix-Vector Broadcasting # Shape (3, 3) + Shape (1, 3) -> Vector broadcasts across every row matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) row_vec = np.array([10, 20, 30]) broadcasted_sum = matrix + row_vec # Result: # [[11, 22, 33], # [14, 25, 36], # [17, 28, 39]]
Shape Mismatch: Attempting arithmetic between incompatible array shapes (e.g., shapes (3, 3) and (2,)) raises a ValueError: frames could not be broadcast together.

4. Mathematical Aggregations & Linear Algebra

NumPy provides optimized mathematical methods that operate over the entire array or along designated axes (e.g., axis=0 for columns, axis=1 for rows).

import numpy as np data = np.array([[5, 10], [15, 20]]) print("Total Sum:", np.sum(data)) # Output: 50 print("Column Means:", np.mean(data, axis=0)) # Output: [10., 15.] print("Row Maxima:", np.max(data, axis=1)) # Output: [10, 20] # Matrix Multiplication (Dot Product) A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) product = np.matmul(A, B) # Equivalent to A @ B

🏋️ Try It Yourself: Practice Challenges

Challenge 1: Normalized Array Scaling

Create a 1D array of 10 random integers between 1 and 100. Write code to scale all elements so they lie strictly in the range $[0.0, 1.0]$ using min-max normalization: $\frac{x - \text{min}}{\text{max} - \text{min}}$.

Challenge 2: Chessboard Matrix Pattern

Construct an $8 \times 8$ matrix filled with alternating 0s and 1s using slicing operations, producing an $8 \times 8$ chessboard layout.

Challenge 3: Row-wise Z-Score Standardization

Create a $4 \times 3$ matrix of numbers. Standardize each column by subtracting its mean and dividing by its standard deviation using np.mean and np.std with axis=0.

⚡ Interactive Sandbox (NumPy Execution Engine)
Console Output:
Click "Run Code" above to execute the NumPy script...

📝 Knowledge Check Quiz

1. Why are NumPy ndarrays faster than standard Python lists for numeric processing?
2. What axis parameter must be provided to aggregate values down each column across all rows?
3. What array shape result is produced when broadcasting a (3, 1) matrix with a (1, 4) vector?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)