21. NumPy for Numerical Computing
What Is NumPy?
NumPy is a fundamental Python library for numerical computing. It provides the `ndarray` — a fast, efficient, multidimensional array object — and tools for mathematical operations, linear algebra, and random number generation.
Installing NumPy
pip install numpyCreating NumPy Arrays
NumPy arrays are similar to Python lists but more efficient for numerical operations. You can create arrays from lists or use built-in functions.
import numpy as np
# From a list
arr = np.array([1, 2, 3, 4, 5])
print(arr)
# Using built-in functions
zeros = np.zeros((3, 3))
ones = np.ones((2, 4))
randoms = np.random.rand(2, 3)
print(zeros, ones, randoms)Array Operations and Vectorization
NumPy allows element-wise operations without loops. This vectorization makes computations faster and cleaner.
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Element-wise addition
print(a + b)
# Element-wise multiplication
print(a * b)
# Scalar operations
print(a * 10)Indexing and Slicing
You can access elements, rows, columns, or subarrays using indexing and slicing, similar to Python lists but more powerful for multi-dimensional arrays.
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Access element
print(matrix[0, 1]) # row 0, col 1
# Slice row
print(matrix[1, :])
# Slice column
print(matrix[:, 2])Broadcasting
Broadcasting lets NumPy perform operations on arrays of different shapes by automatically expanding them to be compatible.
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([10, 20, 30])
print(a + b) # b is broadcasted to match a's shapeCommon Mathematical Functions
arr = np.array([1, 4, 9, 16])
print(np.sqrt(arr))
print(np.mean(arr))
print(np.sum(arr))
print(np.max(arr))
print(np.min(arr))Best Practices
- Prefer NumPy arrays over Python lists for numerical computation.
- Use vectorized operations instead of loops for performance.
- Leverage built-in NumPy functions rather than writing custom math operations.
- Understand broadcasting to avoid shape errors.
Common Misconceptions
- NumPy is only for large datasets — even small arrays benefit from speed.
- You can’t mix Python lists and NumPy arrays directly in arithmetic; convert lists first.
- Slicing a NumPy array creates a view, not a copy. Modifying the slice changes the original array.
Mini Project Step
Create a 5x5 matrix of random numbers, calculate the row-wise mean, column-wise sum, and generate a new matrix where each element is squared. Explore slicing to extract submatrices.