Lecture 2: NumPy Operations, Broadcasting, and Functions
Estimated: 40-50 minutes
1. Array Operations
NumPy supports element-wise operations on arrays of the same shape:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise operations
print("Addition:", a + b) # [5 7 9]
print("Subtraction:", b - a) # [3 3 3]
print("Multiplication:", a * b) # [ 4 10 18]
print("Division:", b / a) # [4. 2.5 2. ]
print("Exponentiation:", a ** 2) # [1 4 9]
Note: These operations are performed element-wise, unlike matrix multiplication.
2. Broadcasting
NumPy can perform operations on arrays of different shapes through broadcasting:
# Array and scalar
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Array + 2:\n", arr + 2)
# Arrays with different dimensions
a = np.array([[1, 2, 3]])
b = np.array([[1], [2], [3]])
print("\nBroadcasted addition:\n", a + b)
Broadcasting Rules:
Dimensions are compared from right to left
Dimensions must be equal or one of them must be 1
Arrays with fewer dimensions are padded with 1's on the left
3. Universal Functions (ufuncs)
NumPy provides fast element-wise operations through universal functions:
data = np.array([[3, 1, 4], [1, 5, 9], [2, 6, 5]])
print("Sum:", np.sum(data))
print("Sum along rows:", np.sum(data, axis=0)) # Sum of each column
print("Sum along columns:", np.sum(data, axis=1)) # Sum of each row
print("\nMean:", np.mean(data))
print("Median:", np.median(data))
print("Standard deviation:", np.std(data))
print("Variance:", np.var(data))
print("Min:", np.min(data))
print("Max:", np.max(data))
print("Index of max:", np.argmax(data)) # Index of flattened array
print("Indices of max in each row:", np.argmax(data, axis=1))
5. Sorting and Searching
Efficient sorting and searching operations:
arr = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5])
# Sorting
print("Sorted array:", np.sort(arr)) # Returns new array
arr.sort() # In-place sort
print("After in-place sort:", arr)
# Searching
print("Indices of elements > 3:", np.where(arr > 3))
print("First index of 5:", np.where(arr == 5)[0][0])
print("Count of 5s:", np.count_nonzero(arr == 5))
print("Check if any > 8:", np.any(arr > 8))
print("Check if all > 0:", np.all(arr > 0))
6. Special Functions
NumPy provides various special mathematical functions:
x = np.linspace(0, 2, 5) # 5 points from 0 to 2
# Bessel functions
from numpy import pi, sin, cos, exp
print("Sine integral:", np.sinc(x))
print("Factorials:", np.math.factorial(5)) # 120
# Linear algebra
from numpy.linalg import inv, det, eig
a = np.array([[1, 2], [3, 4]])
print("\nMatrix inverse:\n", inv(a))
print("Determinant:", det(a))
print("Eigenvalues and eigenvectors:\n", eig(a))
7. Practice Exercise
Given the following array of student scores (out of 100) for 5 subjects: