NumPy Cheatsheet

NumPy array creation, indexing, math operations, and linear algebra with examples

The NumPy cheatsheet covers array creation, indexing and slicing, shape operations, math, broadcasting, linear algebra, and aggregation functions. Search and copy any example.

How to Use This NumPy Cheatsheet

NumPy (Numerical Python) is the foundation of scientific computing in Python. It provides fast n-dimensional arrays and a library of mathematical functions. Almost every data science library (pandas, scikit-learn, PyTorch) uses NumPy arrays under the hood.

Why NumPy is Fast

NumPy arrays are stored in contiguous memory blocks and operations are implemented in C. A vectorized operation like arr * 2 is 100-500x faster than a Python loop. Always prefer vectorized operations over loops when working with arrays.

Broadcasting Rules

Broadcasting allows operations between arrays of different shapes. Arrays are compatible when dimensions match from the right, or one dimension is 1. Example: adding a (3,4) array with a (4,) array — the (4,) is broadcast across 3 rows.

Views vs Copies

Slicing returns a view (changes affect the original). Use arr.copy() to make an independent copy. Boolean and fancy indexing always return copies.

Frequently Asked Questions

Is this NumPy cheatsheet free?

Yes, completely free. All code examples are copyable.

What is the difference between a Python list and a NumPy array?

NumPy arrays are homogeneous (all same type), fixed-size, and stored in contiguous memory — making operations 100x-1000x faster than Python lists. Lists support mixed types and dynamic sizing. For math operations, always use NumPy arrays. For heterogeneous data, use lists or pandas DataFrames.

What is NumPy broadcasting?

Broadcasting lets NumPy apply operations between arrays of different shapes without explicit loops. The smaller array is virtually expanded to match the larger one. Rules: dimensions are aligned from right, sizes must match or one must be 1. Example: adding a (3,4) array with a (4,) array works because the (4,) is broadcast across rows.

How does NumPy indexing work?

Basic: arr[0], arr[1:5], arr[::2]. Multi-dim: arr[0, 1] or arr[0][1]. Boolean: arr[arr > 5] returns elements where condition is True. Fancy: arr[[1,3,5]] selects specific indices. Boolean indexing is the most powerful for data filtering and is equivalent to pandas .loc with conditions.

What is the difference between np.copy() and view?

Basic indexing (slicing) returns a view — changes modify the original array. Fancy indexing (boolean, integer arrays) returns a copy. arr.copy() always makes an independent copy. When in doubt about whether you have a view, check arr.base is not None (True = it's a view).