Python NumPy Cheat Sheet
np.array, np.arange or np.zeros, select with a[1:4] or a[a > 25], and summarise with a.sum() or m.sum(axis=0).Use this page when you know what you want to do with an array but not the exact call. Each table lists a task, the code and the result you get, so you can scan, copy and move on. If a row is new to you, start with NumPy basics and come back; the indexing and math lessons explain the ideas behind the tables.
Install with pip install numpy, then import numpy as np. The examples below run in the browser and were checked against NumPy 2.
Create NumPy arrays: array, zeros, arange and linspace
Every array starts from one of these constructors. In every table, import numpy as np, a = np.array([10, 20, 30, 40, 50]) and m = np.arange(1, 7).reshape(2, 3) (rows [1 2 3] and [4 5 6]). Results are shown as print() would show them. See NumPy basics for what an array is and why it is faster than a list.
| Task | Code | Result |
|---|---|---|
| Array from a list | np.array([1, 2, 3]) | [1 2 3] |
| Zeros | np.zeros(3) | [0. 0. 0.] |
| Ones (2x2) | np.ones((2, 2)) | [[1. 1.] [1. 1.]] |
| Range with a step | np.arange(0, 10, 3) | [0 3 6 9] |
| Evenly spaced points | np.linspace(0, 1, 5) | [0. 0.25 0.5 0.75 1. ] |
| Fill with one value | np.full(3, 7) | [7 7 7] |
| Identity matrix | np.eye(2) | [[1. 0.] [0. 1.]] |
| Reshape 1-D to 2-D | np.arange(6).reshape(2, 3) | [[0 1 2] [3 4 5]] |
| Zeros shaped like another array | np.zeros_like(a) | [0 0 0 0 0] |
NumPy array shape, dtype and reshape
Check shape and dtype first when a result looks wrong; most NumPy errors are shape mismatches. Learn more in NumPy basics.
| Task | Code | Result |
|---|---|---|
Shape of m | m.shape | (2, 3) |
| Number of dimensions | m.ndim | 2 |
| Total number of elements | m.size | 6 |
Data type of a | a.dtype | int64 (on most systems) |
| Convert to float | a.astype(float) | [10. 20. 30. 40. 50.] |
| Flatten to 1-D | m.flatten() | [1 2 3 4 5 6] |
| Transpose | m.T | [[1 4] [2 5] [3 6]] |
| Add a length-1 axis | a[:, None].shape | (5, 1) |
| Let NumPy infer one dimension | np.arange(6).reshape(3, -1).shape | (3, 2) |
NumPy indexing and slicing
Indexing works like list slicing with one extra rule: separate the axes with commas, rows first. Slices are views, so editing them edits the original. The full story is in NumPy indexing.
| Task | Code | Result |
|---|---|---|
| First element | a[0] | 10 |
| Last element | a[-1] | 50 |
| Slice | a[1:4] | [20 30 40] |
| Every second element | a[::2] | [10 30 50] |
| Reverse | a[::-1] | [50 40 30 20 10] |
Row 1 of m | m[1] | [4 5 6] |
One cell of m | m[1, 2] | 6 |
Column 0 of m | m[:, 0] | [1 4] |
| Fancy indexing | a[[0, 2, 4]] | [10 30 50] |
NumPy boolean masks and np.where
Comparisons give an array of True/False; use it as an index to filter. Combine conditions with & and | (not and/or) and put each condition in parentheses. See NumPy indexing.
| Task | Code | Result |
|---|---|---|
| Boolean mask | a > 25 | [False False True True True] |
| Filter with a mask | a[a > 25] | [30 40 50] |
Two conditions (use &) | a[(a > 15) & (a < 45)] | [20 30 40] |
Either condition (use |) | a[(a < 20) | (a > 40)] | [10 50] |
| Count matches | (a > 25).sum() | 3 |
| Indices where true | np.where(a > 25)[0] | [2 3 4] |
| Choose between two values | np.where(a > 25, "big", "small") | ['small' 'small' 'big' 'big' 'big'] |
| Clip to a range | np.clip(a, 15, 45) | [15 20 30 40 45] |
| Is any element true? | (a > 25).any() | True |
| Are all elements true? | (a > 25).all() | False |
NumPy math and statistics
Operations apply to every element at once, with no loop. Pair them with the NumPy math lesson for the details.
| Task | Code | Result |
|---|---|---|
| Add a number to every element | a + 5 | [15 25 35 45 55] |
| Multiply every element | a * 2 | [ 20 40 60 80 100] |
| Element-wise sum of two arrays | a + np.array([1, 1, 1, 1, 1]) | [11 21 31 41 51] |
| Square root | np.sqrt(np.array([4, 9, 16])) | [2. 3. 4.] |
| Power | np.array([1, 2, 3]) ** 2 | [1 4 9] |
| Sum | a.sum() | 150 |
| Mean | a.mean() | 30.0 |
| Standard deviation | np.round(a.std(), 2) | 14.14 |
| Cumulative sum | a.cumsum() | [ 10 30 60 100 150] |
| Index of the largest value | a.argmax() | 4 |
| Smallest value | a.min() | 10 |
| Largest value | a.max() | 50 |
NumPy axis, broadcasting and matrix product
axis=0 collapses the rows (one result per column); axis=1 collapses the columns (one result per row). Broadcasting stretches a smaller array across a bigger one when the shapes line up. See NumPy math.
| Task | Code | Result |
|---|---|---|
| Sum of all cells | m.sum() | 21 |
Column sums (axis=0) | m.sum(axis=0) | [5 7 9] |
Row sums (axis=1) | m.sum(axis=1) | [ 6 15] |
| Column means | m.mean(axis=0) | [2.5 3.5 4.5] |
| Row maximums | m.max(axis=1) | [3 6] |
| Broadcast a row over rows | m + np.array([10, 20, 30]) | [[11 22 33] [14 25 36]] |
| Broadcast a column over columns | m + np.array([[100], [200]]) | [[101 102 103] [204 205 206]] |
| Matrix product | m @ m.T | [[14 32] [32 77]] |
| Sort each row | np.sort(np.array([[3, 1, 2], [9, 7, 8]]), axis=1) | [[1 2 3] [7 8 9]] |
Join, sort, split and de-duplicate NumPy arrays
These helpers reshape your data pipeline. Remember that each returns a new array and leaves the input alone.
| Task | Code | Result |
|---|---|---|
| Stack end to end | np.concatenate([[1, 2], [3, 4]]) | [1 2 3 4] |
| Stack rows (vertical) | np.vstack([[1, 2], [3, 4]]) | [[1 2] [3 4]] |
| Stack columns (horizontal) | np.hstack([[1, 2], [3, 4]]) | [1 2 3 4] |
| Sort values | np.sort(np.array([3, 1, 2])) | [1 2 3] |
| Indices that would sort | np.argsort(np.array([30, 10, 20])) | [1 2 0] |
| Unique values | np.unique(np.array([3, 1, 3, 2, 1])) | [1 2 3] |
| Split into equal parts | np.split(np.arange(6), 3) | three arrays: [0 1], [2 3], [4 5] |
| Repeat each element | np.repeat([1, 2], 2) | [1 1 2 2] |
| Round decimals | np.round(np.array([1.234, 5.678]), 1) | [1.2 5.7] |
Which NumPy tool should I use?
A quick decision guide.
| If you want to... | Use | Why |
|---|---|---|
| Build a sequence of integers | np.arange | Like range but returns an array |
| Build N evenly spaced decimals | np.linspace | You choose the number of points, not the step |
| Filter by a condition | a[a > x] | A boolean mask keeps only matching elements |
| Pick between two values per element | np.where(cond, x, y) | Vectorised if/else |
| Total per column or row | sum(axis=...) | One result per remaining axis |
| Keep the original array safe | a.copy() | Slices are views and share memory |
| Combine arrays of the same width | np.vstack | Adds rows |
| Combine arrays of the same height | np.hstack | Adds columns |
| Plain Python lists of mixed types | Stay with a list | NumPy arrays hold one dtype |
Examples you can run
Press Run, then edit the code and run it again.
Normalise exam scores with array math
Subtract the mean and divide by the standard deviation with no loop. The np.round call keeps the printout stable.
import numpy as np
scores = np.array([62, 75, 88, 91, 54])
z = (scores - scores.mean()) / scores.std()
print(np.round(z, 2))
print(scores[z > 0])Expected output[-0.84 0.07 0.98 1.18 -1.39]
[75 88 91]
Column totals and filtering a 2-D array
Rows are days, columns are products. axis=0 gives a total per product, and a mask picks the busy days.
import numpy as np
sales = np.array([[5, 2, 7], [3, 8, 1], [6, 4, 9]])
print(sales.sum(axis=0))
print(sales.sum(axis=1))
busy = sales.sum(axis=1) > 15
print(busy)
print(sales[busy])Expected output[14 14 17]
[14 12 19]
[False False True]
[[6 4 9]]
Broadcasting a price list over a cart
A 1-D array of prices is stretched across every row of the quantity grid.
import numpy as np
qty = np.array([[1, 2, 3], [4, 5, 6]])
price = np.array([2.5, 1.0, 4.0])
totals = qty * price
print(totals)
print(totals.sum(axis=1))Expected output[[ 2.5 2. 12. ]
[10. 5. 24. ]]
[16.5 39. ]
Common mistakes
Using `and` instead of `&` in a mask
✗ Wrong
import numpy as np
a = np.array([10, 20, 30])
print(a[(a > 10) and (a < 30)])✓ Right
import numpy as np
a = np.array([10, 20, 30])
print(a[(a > 10) & (a < 30)])Python's and wants one True/False. Use & with parentheses to compare element by element.
Adding arrays with different shapes
✗ Wrong
import numpy as np
print(np.array([1, 2, 3]) + np.array([1, 2]))✓ Right
import numpy as np
print(np.array([1, 2, 3]) + np.array([1, 2, 3]))Shapes must match or be broadcastable (equal, or one of them 1). Check .shape and reshape or slice.
Python NumPy Cheat Sheet: questions people ask
What is the difference between np.arange and np.linspace?
np.arange(start, stop, step) takes a step size and excludes stop, while np.linspace(start, stop, num) takes the number of points and includes stop. Use linspace for decimals to avoid floating-point surprises.
How do I install NumPy?
Run pip install numpy in your terminal, then import numpy as np in your code. In the browser editor on this site, list numpy as a package and it is loaded for you.
What does axis=0 mean in NumPy?
axis=0 runs down the rows, so m.sum(axis=0) returns one total per column. axis=1 runs across the columns and returns one total per row. See NumPy math for diagrams of this idea.
Keep learning
Step-by-step lessons:
NumPy BasicsNumPy Indexing and SlicingNumPy Math and Broadcasting
Related:
Python pandas Cheat SheetPandas BasicsPython Lists
More in data tools:
Python pandas Cheat Sheet See all →