Cheat sheetData tools

Python NumPy Cheat Sheet

Short answer
NumPy stores numbers in fixed-type arrays and applies operations to every element at once: build with 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.

Array creation functions
TaskCodeResult
Array from a listnp.array([1, 2, 3])[1 2 3]
Zerosnp.zeros(3)[0. 0. 0.]
Ones (2x2)np.ones((2, 2))[[1. 1.] [1. 1.]]
Range with a stepnp.arange(0, 10, 3)[0 3 6 9]
Evenly spaced pointsnp.linspace(0, 1, 5)[0. 0.25 0.5 0.75 1. ]
Fill with one valuenp.full(3, 7)[7 7 7]
Identity matrixnp.eye(2)[[1. 0.] [0. 1.]]
Reshape 1-D to 2-Dnp.arange(6).reshape(2, 3)[[0 1 2] [3 4 5]]
Zeros shaped like another arraynp.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.

Array attributes and reshaping
TaskCodeResult
Shape of mm.shape(2, 3)
Number of dimensionsm.ndim2
Total number of elementsm.size6
Data type of aa.dtypeint64 (on most systems)
Convert to floata.astype(float)[10. 20. 30. 40. 50.]
Flatten to 1-Dm.flatten()[1 2 3 4 5 6]
Transposem.T[[1 4] [2 5] [3 6]]
Add a length-1 axisa[:, None].shape(5, 1)
Let NumPy infer one dimensionnp.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.

Indexing, slicing and fancy indexing
TaskCodeResult
First elementa[0]10
Last elementa[-1]50
Slicea[1:4][20 30 40]
Every second elementa[::2][10 30 50]
Reversea[::-1][50 40 30 20 10]
Row 1 of mm[1][4 5 6]
One cell of mm[1, 2]6
Column 0 of mm[:, 0][1 4]
Fancy indexinga[[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.

Filtering with conditions
TaskCodeResult
Boolean maska > 25[False False True True True]
Filter with a maska[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 truenp.where(a > 25)[0][2 3 4]
Choose between two valuesnp.where(a > 25, "big", "small")['small' 'small' 'big' 'big' 'big']
Clip to a rangenp.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.

Element-wise maths and summary statistics
TaskCodeResult
Add a number to every elementa + 5[15 25 35 45 55]
Multiply every elementa * 2[ 20 40 60 80 100]
Element-wise sum of two arraysa + np.array([1, 1, 1, 1, 1])[11 21 31 41 51]
Square rootnp.sqrt(np.array([4, 9, 16]))[2. 3. 4.]
Powernp.array([1, 2, 3]) ** 2[1 4 9]
Suma.sum()150
Meana.mean()30.0
Standard deviationnp.round(a.std(), 2)14.14
Cumulative suma.cumsum()[ 10 30 60 100 150]
Index of the largest valuea.argmax()4
Smallest valuea.min()10
Largest valuea.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.

Working along an axis
TaskCodeResult
Sum of all cellsm.sum()21
Column sums (axis=0)m.sum(axis=0)[5 7 9]
Row sums (axis=1)m.sum(axis=1)[ 6 15]
Column meansm.mean(axis=0)[2.5 3.5 4.5]
Row maximumsm.max(axis=1)[3 6]
Broadcast a row over rowsm + np.array([10, 20, 30])[[11 22 33] [14 25 36]]
Broadcast a column over columnsm + np.array([[100], [200]])[[101 102 103] [204 205 206]]
Matrix productm @ m.T[[14 32] [32 77]]
Sort each rownp.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.

Combining and ordering arrays
TaskCodeResult
Stack end to endnp.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 valuesnp.sort(np.array([3, 1, 2]))[1 2 3]
Indices that would sortnp.argsort(np.array([30, 10, 20]))[1 2 0]
Unique valuesnp.unique(np.array([3, 1, 3, 2, 1]))[1 2 3]
Split into equal partsnp.split(np.arange(6), 3)three arrays: [0 1], [2 3], [4 5]
Repeat each elementnp.repeat([1, 2], 2)[1 1 2 2]
Round decimalsnp.round(np.array([1.234, 5.678]), 1)[1.2 5.7]

Which NumPy tool should I use?

A quick decision guide.

Choosing between similar NumPy functions
If you want to...UseWhy
Build a sequence of integersnp.arangeLike range but returns an array
Build N evenly spaced decimalsnp.linspaceYou choose the number of points, not the step
Filter by a conditiona[a > x]A boolean mask keeps only matching elements
Pick between two values per elementnp.where(cond, x, y)Vectorised if/else
Total per column or rowsum(axis=...)One result per remaining axis
Keep the original array safea.copy()Slices are views and share memory
Combine arrays of the same widthnp.vstackAdds rows
Combine arrays of the same heightnp.hstackAdds columns
Plain Python lists of mixed typesStay with a listNumPy 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.

Normalise exam scores with array math
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.

Column totals and filtering a 2-D array
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.

Broadcasting a price list over a cart
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)])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

✓ 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]))
ValueError: operands could not be broadcast together with shapes (3,) (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 →