NumPy Cheat Sheet

NumPy reference guide — arrays, broadcasting, indexing, universal functions, linear algebra, and essential scientific computing operations in Python.

Last Updated: July 15, 2025

Creating Arrays

FunctionResult
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

OperationExample
Basic slicearr[2:5] — rows 2,3,4
Fancy indexingarr[[0,2,4]] — rows at indices 0,2,4
Boolean maskarr[arr > 5] — all values > 5
Multi-dimarr[:, 1:3] — all rows, columns 1-2

Broadcasting

RuleExample
Scalar broadcastarr + 5 — adds 5 to every element
Row vectorarr + np.array([1,2,3]) — added per column
Column vectorarr + np.array([[1],[2],[3]]) — per row

Key Functions

FunctionPurpose
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.
← Back to Programming Languages | Browse all categories | View all cheat sheets