Creating Arrays
| Function | Result |
np.array([1,2,3]) | 1D array from list |
np.zeros((3,4)) | 3x4 array of zeros |
np.ones((2,3)) | 2x3 array of ones |
np.arange(0,10,2) | [0,2,4,6,8] |
np.linspace(0,1,5) | [0, 0.25, 0.5, 0.75, 1.0] |
np.random.rand(3,3) | 3x3 random values [0,1) |
Indexing & Slicing
| Operation | Example |
| Basic slice | arr[2:5] — rows 2,3,4 |
| Fancy indexing | arr[[0,2,4]] — rows at indices 0,2,4 |
| Boolean mask | arr[arr > 5] — all values > 5 |
| Multi-dim | arr[:, 1:3] — all rows, columns 1-2 |
Broadcasting
| Rule | Example |
| Scalar broadcast | arr + 5 — adds 5 to every element |
| Row vector | arr + np.array([1,2,3]) — added per column |
| Column vector | arr + np.array([[1],[2],[3]]) — per row |
Key Functions
| Function | Purpose |
arr.reshape(2,6) | Reshape to 2x6 |
np.dot(a, b) | Matrix multiplication |
np.mean(arr, axis=0) | Mean along axis 0 (columns) |
np.concatenate([a,b]) | Join arrays |
Pro Tip: Vectorize everything. A NumPy operation on an entire array is 10-100x faster than a Python for loop over elements. If you find yourself writing a loop over array elements, there's almost certainly a vectorized alternative.