NumPy Arrays & Mathematical Operations
Learn vectorization and high-performance mathematical operations with NumPy.
Why NumPy?
Python lists are slow for large-scale numerical work. NumPy provides arrays that are efficient, stored in contiguous memory, and support vectorized operations (avoiding explicit loops).
Creating Arrays
import numpy as np
# From a list
arr = np.array([1, 2, 3, 4])
# Built-in generators
zeros = np.zeros((3, 3)) # 3x3 matrix
sequence = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
# From a list
arr = np.array([1, 2, 3, 4])
# Built-in generators
zeros = np.zeros((3, 3)) # 3x3 matrix
sequence = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
Vectorization
Perform operations on whole arrays without writing loops.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = a + b # [5, 7, 9]
d = a * 2 # [2, 4, 6]
b = np.array([4, 5, 6])
c = a + b # [5, 7, 9]
d = a * 2 # [2, 4, 6]
Indexing and Slicing
matrix = np.random.rand(5, 5)
# Select row 0
row0 = matrix[0, :]
# Select a 2x2 sub-block
block = matrix[0:2, 0:2]
# Select row 0
row0 = matrix[0, :]
# Select a 2x2 sub-block
block = matrix[0:2, 0:2]
Universal Functions (ufuncs)
NumPy includes optimized math functions like sin, cos, exp, and log.
angles = np.array([0, np.pi/2, np.pi])
sines = np.sin(angles)
sines = np.sin(angles)
โ Practice (15 minutes)
- Create a 1D array of 10 random integers between 1 and 100.
- Calculate the mean and standard deviation of your array.
- Create a 4x4 identity matrix using
np.eye. - Perform element-wise multiplication of two 3x3 matrices.