import numpy as np
A = np.arange(25).reshape((5, 5))
print("Original:")
print(A)
middle = A[1:4, 1:4]  # Rows 1-3, columns 1-3
every_other = A[::2, :]  # Every 2nd row
reversed_array = A[::-1, ::-1]  # Reverse both
print("\nMiddle 3x3:")
print(middle)
print("\nEvery other row:")
print(every_other)
print("\nReversed:")
print(reversed_array)Numerical Computing with NumPy
Why NumPy?
When we looked at Python data structures, the only way to work with arrays of values (matrices, vectors, etc.) was through lists and lists of lists. This approach is:
- Slow - Python lists aren’t optimized for numerical operations
- Inefficient - Looping over elements wastes time and memory
- Verbose - Simple operations require lots of code
NumPy solves these problems by providing fast,contiguous array storage and vectorized operations.
Creating Arrays
The fundamental NumPy data type is the ndarray (N-dimensional array):
Arrays have important attributes: - dtype - the data type of elements - shape - dimensions of the array - ndim - number of dimensions - size - total number of elements
Multi-dimensional Arrays
Array Indexing and Slicing
NumPy arrays support powerful indexing:
Slicing Operations
The colon : notation is powerful: - A[i, :] - entire row i - A[:, j] - entire column j - A[::2, ::2] - every 2nd element in both dimensions - A[::-1, ::-1] - reverse both dimensions
Why NumPy is Fast: Vectorized Operations
The real power of NumPy comes from vectorized operations - operations on entire arrays without explicit loops:
Element-wise Operations
NumPy operations work element-by-element:
Array Reshaping and Views
NumPy can show you the same data in different shapes without copying:
The -1 in reshape means “figure out this dimension automatically”:
Most NumPy operations create views (references to the same data), not copies. This is efficient but can be surprising:
To make an independent copy, use .copy():
B = A.copy()Broadcasting
Broadcasting allows operations between arrays of different shapes:
Broadcasting rules: 1. Arrays don’t need the same shape 2. Dimensions are compared element-wise from right to left 3. Dimensions are compatible if they’re equal or one of them is 1
Useful Array Creation Functions
Array Mathematics
NumPy provides comprehensive mathematical functions:
Linear Algebra
Summary
NumPy provides: - Fast arrays - Contiguous memory, optimized operations - Vectorization - Operations on entire arrays - Broadcasting - Automatic dimension matching - Mathematical functions - Comprehensive library - Linear algebra - Matrix operations built-in
NumPy is the foundation of scientific Python. Almost every scientific package (SciPy, matplotlib, pandas) builds on NumPy arrays.
