NumPy Basics
NumPy Basics
DIBS Methods Meetings · Jim Zhang
NumPy is the foundational library that everything in the Python scientific ecosystem is built on (including PsychoPy):

Figure 2 from Harris et al. (2020), Array programming with NumPy, Nature 585, 357-362. Licensed under CC BY 4.0.
We will be playing around with NumPy arrays, the core data structure of NumPy. NumPy arrays are basically grids that can be 1D, 2D, etc., consisting of data elements in each cell. We’ll build our own arrays, then load a raccoon’s face represented as a rows x columns x color channels array, and perform a bunch of operations on it (e.g., indexing and slicing, masks, reshaping, aggregating along axes, broadcasting).
Table of Contents
- The
ndarray: what an array is and why it’s fast - Indexing and slicing: cropping, flipping, and pulling out channels
- Boolean masks and
np.where: selecting pixels by what they look like - Reshaping: turning an image into a list of pixels
- Aggregating along axes: averaging away a dimension
- Broadcasting: math between arrays of different shapes, without loops
1
2
3
import numpy as np # we conventionally import numpy as np
import matplotlib.pyplot as plt # for plotting
from scipy import datasets # grab raccoon from here
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%config InlineBackend.figure_formats = ["jpeg"] # keeps the notebook small with this many photos
print("NumPy version:", np.__version__)
def show(*images, titles=None, size=4):
# Helper function to display one or more images side by side. See Miles' tutorial on plotting in python for a detailed explanation of this stuff.
fig, axes = plt.subplots(1, len(images), figsize=(size * len(images), size * 0.75))
axes = np.atleast_1d(axes)
for i, (ax, img) in enumerate(zip(axes, images)):
ax.imshow(img, cmap="gray")
ax.axis("off")
if titles:
ax.set_title(titles[i], family="monospace", fontsize=10)
plt.tight_layout()
plt.show()
1
NumPy version: 1.24.2
1. The ndarray
A NumPy array is an alternative to Python lists. Python lists are slow to operate on, because they can contain mixed types of data (e.g., floats, ints, strings), and thus must represent each element as a full Python object with its own type info, reference count, and other info. However, when all variables in a list are of the same type (e.g., all ints), most of this info is redundant and so we can just store the data as one contiguous block in memory and have one pointer to it, rather than a pointer to every single variable individually. This reduces memory usage and speeds up computations.
A NumPy array is thus a block of memory plus a little metadata saying how to read it: its shape, its data type (dtype), and how many bytes to step to get from one element to the next (strides). Unlike a Python list, every element has the same type and sits next to the others in memory. That’s why NumPy can run fast compiled loops over the data.

ok let’s distort a raccoon’s face (represented as a rows x columns x color array) now :D
first, let’s load the face array and inspect it’s properties
1
2
3
4
5
6
7
8
9
10
11
face = datasets.face()
print("shape: ", face.shape) # (rows, columns, color channels)
print("ndim: ", face.ndim)
print("dtype: ", face.dtype) # unsigned 8-bit integers: 0-255
print("size: ", face.size) # 768 * 1024 * 3 numbers
print("memory: ", face.nbytes / 1e6, "MB")
print("strides:", face.strides) # bytes to step along each axis
plt.imshow(face)
plt.axis("off")
plt.show()
1
2
3
4
5
6
shape: (768, 1024, 3)
ndim: 3
dtype: uint8
size: 2359296
memory: 2.359296 MB
strides: (3072, 3, 1)

Each pixel is three numbers: how much red, green, and blue light it has, from 0 (none) to 255 (full).
1
print(face[300, 700]) # one pixel: [R, G, B]
1
[142 132 143]
Making arrays yourself
1
2
3
4
5
6
7
8
9
10
11
12
13
14
x = np.array([1,2,3,4,5]) # initialize an array using a python sequence, like a list
print(x)
print(np.zeros(5)) # initialize an array of 5 zeroes
print(np.arange(0, 10, 2)) # like range(), but returns an array
print(np.linspace(0, 1, 5)) # 5 evenly spaced points from 0 to 1, endpoints included
canvas = np.zeros((100, 150, 3), dtype=np.uint8) # a black image
ramp = np.tile(np.linspace(0, 255, 150).astype(np.uint8), (100, 1)) # a left-to-right gradient
rng = np.random.default_rng(seed=2026) # the modern way to get random numbers
static = rng.integers(0, 256, size=(100, 150, 3), dtype=np.uint8) # TV static
show(canvas, ramp, static, titles=["np.zeros", "np.linspace", "rng.integers"], size=3)
1
2
3
4
[1 2 3 4 5]
[0. 0. 0. 0. 0.]
[0 2 4 6 8]
[0. 0.25 0.5 0.75 1. ]

NumPy is fast!
Let’s compute the raccoon’s average brightness with a plain Python loop and then with NumPy. We see it’s almost 30x faster to use NumPy! Not a big deal for the raccoon face since it’s not that much data, but you can imagine if you have an iEEG dataset with 1 hour of data per subject, and 10 subjects with 100 channels each sampled at 2048 samples per second that your computational time (and memory) would start to get out of hand if you were to use lists instead of NumPy arrays, especially if you’re chaining together a bunch of complicated analyses.
1
2
3
4
5
def python_mean(xs):
total = 0
for x in xs:
total += x
return total / len(xs)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
values = face.ravel().tolist() # all 2.4 million numbers as an ordinary Python list
print(f'first few values: {values[0:5]}')
def python_mean(xs):
# helper function to get the mean of xs, which is a list.
total = 0
for x in xs:
total += x
return total / len(xs)
print(python_mean(values), face.mean())
%timeit python_mean(values)
%timeit face.mean()
1
2
3
4
first few values: [121, 112, 131, 138, 129]
110.16274388631184 110.16274388631184
30.4 ms ± 1.35 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
669 µs ± 5.89 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
NumPy is faster because it runs compiled C code instead of Python. Writing code that works on whole arrays at once is called vectorization, and it’s a good habit to get into when working with large amounts of data.
2. Indexing and slicing
Indexing a 3-D array takes up to three positions: face[row, column, channel]. A slice start:stop:step picks a range along one axis.
Note that NumPy counts from 0 and slices exclude the stop index. This is different than MATLAB, which counts from 1 and slices include the stop index. I think that makes more sense tbh. But MATLAB still sucks.
1
2
3
print(face[0, 0]) # top-left pixel
print(face[-1, -1]) # bottom-right pixel
print(face[0, :5, 0]) # red values of the first 5 pixels in the top row
1
2
3
[121 112 131]
[118 154 92]
[121 138 153 155 155]
1
2
3
4
5
6
7
crop = face[0:200, 0:200, :] # top left corner of the image
flip = face[::-1, :, :] # step of -1 along rows: upside down
mirror = face[:, ::-1, :] # step of -1 along columns: left-right mirror
pixel = face[::16, ::16, :] # every 16th row and column
show(crop, flip, mirror, pixel,
titles=["face[220:520, 520:900]", "face[::-1, :, :]", "face[:, ::-1, :]", "face[::16, ::16, :]"])

The last axis holds the color channels, so face[:, :, 0] is a 2-D array of just the red values. ... (Ellipsis) means “all the axes I didn’t mention,” so face[..., 0] is the same thing.
1
2
3
red, green, blue = face[..., 0], face[..., 1], face[..., 2]
print(red.shape)
show(red, green, blue, titles=["face[..., 0] red", "face[..., 1] green", "face[..., 2] blue"])
1
(768, 1024)

Bright = lots of that color. The leaves are brightest in the green channel, and the white fur is bright in all three.
Don’t accidentally break your data! - views vs. copies
Slicing gives a view, a window onto the same memory. SO If you edit a view, you edit the original. You have to explicitly copy your slice to not do this on accident.
1
2
3
4
5
6
img = face.copy() # work on a copy so we don't damage `face`
nose = img[400:480, 600:700] # a slice: a view into img
nose[...] = [255, 0, 0] # paint the view red for all pixels in this slice
show(img, titles=["painting the view painted the original"])

1
2
3
4
img = face.copy()
nose = img[400:480, 600:700].copy() # an explicit copy!
nose[...] = [255, 0, 0] # ...now only the copy changes
print("original untouched:", np.array_equal(img, face))
1
original untouched: True
3. Boolean masks and np.where
A comparison on an array gives a boolean array of the same shape: True where the condition holds. You can use this mask to select, count, or replace elements, like if you want to get rid of NaN trials.
1
2
3
4
5
6
7
gray = face.mean(axis=2) # (768, 1024): average the three channels (more on axis= later)
bright = gray > 180 # True wherever the pixel is bright
print(bright.shape, bright.dtype)
print("fraction of bright pixels:", bright.mean()) # True counts as 1, False as 0
show(gray, bright, titles=['gray', 'gray > 180'])
1
2
(768, 1024) bool
fraction of bright pixels: 0.10821151733398438

Masks combine with & (and), | (or), and ~ (not). Wrap each comparison in parentheses.
Make sure to use &, |, ~ on arrays, not Python’s and, or, not. The former operates on array elements, one at atime. The latter operates on the array as a whole, and will thus try to turn the whole array into a single True/False, raising an error.
Let’s find the leaves: pixels that are clearly greener than they are red or blue. (We convert to int first so subtraction can go negative; see the uint8 gotcha in Section 8.)
1
2
3
4
5
6
7
8
r, g, b = (face[..., i].astype(int) for i in range(3))
leaves = (g > r + 15) & (g > b + 15)
print(f"{leaves.mean():.0%} of the photo is leaves")
print("average color of leaf pixels: ", face[leaves].mean(axis=0).round())
print("average color of non-leaf pixels:", face[~leaves].mean(axis=0).round())
show(leaves, titles=["leaves"])
1
2
3
31% of the photo is leaves
average color of leaf pixels: [110. 141. 78.]
average color of non-leaf pixels: [111. 107. 113.]

face[leaves] uses a 2-D mask on a 3-D array. It picks out the matching pixels, each with its 3 color values, so the result has shape (n_leaf_pixels, 3). Masking drops everything else.
If we want to keep the image’s shape and just change some pixels, use np.where(condition, if_true, if_false). Here we keep the leaves in color and turn the raccoon gray:
1
2
3
4
gray3 = np.stack([gray, gray, gray], axis=-1).astype(np.uint8) # gray, but with 3 channels
look_at_the_raccoon = np.where(leaves[..., np.newaxis], face, gray3) # leaves from face, the rest from gray3
show(face, look_at_the_raccoon, titles=["face", "np.where(leaves, face, gray)"])

Fancy indexing: index with a list of positions
Instead of a slice, you can pass a list of indices. Reordering the color channels is one line:
1
2
3
4
5
swapped = face[..., [2, 1, 0]] # channels in the order blue, green, red
odd_rows = face[[0, 100, 200, 300], :, :] # just these four rows -> shape (4, 1024, 3)
print(odd_rows.shape)
show(swapped, titles=["face[..., [2, 1, 0]]"])
1
(4, 1024, 3)

4. Reshaping
reshape converts an array into a new shape. The total number of elements has to stay the same though, but you can do -1, which means “just figure out the shape for me”.
An image as a list of pixels
1
2
3
4
5
6
7
8
print(f'original shape: {face.shape}')
pixels = face.reshape(786432, 3) # (786432, 3): one row per pixel, one column per channel
pixels2 = face.reshape(-1, 3) # this does the same thing but you don't have to do the math yourself
print(f'new shape: {pixels.shape}')
print(f'are these the same thing: {np.array_equal(pixels, pixels2)}')
1
2
3
original shape: (768, 1024, 3)
new shape: (786432, 3)
are these the same thing: True
5. Aggregating along axes
Every reduction (mean, median, std, sum, max, …) takes an axis argument. A helpful way to think about it: axis is the dimension that disappears (the one you apply the operation over). So if you want to get the average across the rows in each column, you would set axis=0, to end up with 1 value per column. Here is a more complete list of all the aggregation functions you can do to a numpy array.
| Call | Result shape | Meaning |
|---|---|---|
face.mean(axis=2) |
(768, 1024) | average the color channels → grayscale |
face.mean(axis=(0, 1)) |
(3,) | average over all pixels → one mean per color |
gray.mean(axis=1) |
(768,) | average across each row → brightness from top to bottom |
face.mean() |
scalar | one number |
1
2
3
4
5
6
7
8
9
10
11
12
13
print("mean of each channel:", face.mean(axis=(0, 1)).round(1))
print("max of each channel: ", face.max(axis=(0, 1)))
row_profile = gray.mean(axis=1) # (768,)
col_profile = gray.mean(axis=0) # (1024,)
fig, axes = plt.subplots(1, 2, figsize=(10, 3))
axes[0].plot(row_profile)
axes[0].set(xlabel="row (top to bottom)", ylabel="mean brightness", title="gray.mean(axis=1)")
axes[1].plot(col_profile)
axes[1].set(xlabel="column (left to right)", title="gray.mean(axis=0)")
plt.tight_layout()
plt.show()
1
2
mean of each channel: [110.7 117.7 102.1]
max of each channel: [255 252 255]

6. Broadcasting
Broadcasting is how NumPy does arithmetic between arrays of different shapes. It compares shapes from the right. Two dimensions are compatible if they’re equal or if one of them is 1, and a dimension of size 1 (or a missing one) gets “stretched” to match, without copying any data.
1
2
3
4
face (768, 1024, 3)
weights (3,)
-----------------------------
result (768, 1024, 3) one weight per color, applied to every pixel
Here’s a figure showing this for more cases

Figure from Jake VanderPlas, Python Data Science Handbook (adapted from the astroML documentation). Light boxes are the “stretched” values, which NumPy never actually stores.
1
2
3
4
5
6
7
8
weights = np.array([0.7, 0.7, 1.2]) # less red, less green, more blue
print(f'face array shape: {face.shape}')
print(f'weights array shape: {weights.shape}')
bluer = (face * weights).clip(0, 255).astype(np.uint8) # multiply the weights and face arrays - notice that the weights array dimension matches the rightmost dimension of the face array
show(bluer, titles=["face * [0.7, 0.7, 1.2]"])
1
2
face array shape: (768, 1024, 3)
weights array shape: (3,)

if you get broadcasting errors, print the shapes!
Resources (there are a bunch of these online and they are better at explaining things than me)
Official
- NumPy: the absolute basics for beginners (this is pretty nicely written and detailed!!)
- NumPy for MATLAB users
- Broadcasting and Indexing in the NumPy user guide
Tutorials and books
- Jake VanderPlas, Python Data Science Handbook, Ch. 2 (free online - but this entire book is super awesome and probably all you need to know tbh to do most analyses in python!!!)
- Scientific Python Lectures: the NumPy array object (also has a nice image-processing chapter)
- Nicolas Rougier, From Python to NumPy: a free book on vectorization
Earlier DIBS Methods Meetings posts
- Data Wrangling with Python + Pandas: pandas is built on NumPy and what you will likely use more if you’re working with behavioral data
- Plotting in python: python plotting sucks compared to r but miles has tried to ease the pains for us
Citations
- Harris, C. R., et al. (2020). Array programming with NumPy. Nature, 585, 357–362. https://doi.org/10.1038/s41586-020-2649-2
- Raccoon photo:
scipy.datasets.face