NumPy Indexing, Slicing, Masks and np.where
Get values out of a NumPy array by position, by range, by condition and by a list of positions, write through slices, use np.where three ways, and learn which picks are views and which are copies.
What you will learn
- Pick values by position and slice 1D and 2D arrays, row first then column
- Filter with boolean masks and combine conditions with &, | and ~
- Use fancy indexing and np.where to pick, replace and find values
- Know which selections share memory with the original and which are copies
Before you start
- NumPy arrays, shape and dtype
- Python lists and slicing
You can already create an array. Now you'll reach inside it: for one value, for a stretch of values, or for only the values that match a rule. You'll use this in almost every line of NumPy you write.
There are four ways to pick: by position, by a range, by a condition, and by a list of positions. And there's one thing that catches almost everyone, when changing a slice changes the original. All outputs here are from a real run on NumPy 2.5.4.
One value, or a stretch of values
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70])
print(arr[0])
print(arr[-1])
print(arr[2:5])
print(arr[::2])
print(arr[1::2])
print(arr[::-1])
10
70
[30 40 50]
[10 30 50 70]
[20 40 60]
[70 60 50 40 30 20 10]
Counting starts at zero, so 10 is at position 0 and 70 at 6. -1 always means the last cell. A slice is start:stop, and the stop isn't included, so arr[2:5] gives positions 2, 3 and 4. A second colon adds a step: ::2 takes every second value, and a step of -1 walks backward. Leave a number out and NumPy uses the start or the end for you.
Asking for a cell that isn't there
print(arr[6])
print(arr[7])
70
Traceback (most recent call last):
File "S05L02_Indexing\out_of_range.py", line 6, in <module>
print(arr[7])
~~~^^^
IndexError: index 7 is out of bounds for axis 0 with size 7
Seven values means positions 0 to 6. The last position is always the size minus one.
Row first, then column
Think of seats in a cinema. You find the row first, then the seat in that row.
import numpy as np
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print(arr[0, 1])
print(arr[1])
print(arr[:, 0])
print(arr[0:2, 1:3])
print(arr[-1, -1])
2
[5 6 7 8]
[1 5 9]
[[2 3]
[6 7]]
12
Give one number and you get a whole row. For a column, put a colon first: every row, column 0. Slice both directions at once and you get the block where they cross, still two dimensional.
A slice is a view
A slice isn't a new array. It's a frame over the original, with no data of its own.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
s = arr[1:4]
print(s)
s[0] = 999
print(arr)
print(np.shares_memory(arr, s))
[20 30 40]
[ 10 999 30 40 50]
True
We only touched s, and the original changed. NumPy does this on purpose, because copying a large array on every slice would be slow. When you want separate data, ask for it:
safe = arr[1:4].copy()
safe[0] = 0
print(safe)
print(arr)
print(np.shares_memory(arr, safe))
[ 0 30 40]
[10 20 30 40 50]
False
(This run starts from a fresh arr of 10 to 50.) Use a view to read, or to change the original on purpose. Use .copy() when the original has to stay as it is.
Writing through a slice
That sharing is useful, too. Select the cells, then assign:
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
arr[0:2, 1:3] = 0
print(arr)
arr[:, 3] = [40, 80, 120]
print(arr)
[[ 1 0 0 4]
[ 5 0 0 8]
[ 9 10 11 12]]
[[ 1 0 0 40]
[ 5 0 0 80]
[ 9 10 11 120]]
One value fills every selected cell. A list dropped into a column puts one value in each row. No loop anywhere.
Picking by a condition
Often you don't know the positions, only the rule, like "every value above five".
import numpy as np
arr = np.array([1, 5, 3, 8, 2, 9, 4, 7])
mask = arr > 5
print(mask)
print(arr[mask])
print(arr[arr > 5])
[False False False True False True False True]
[8 9 7]
[8 9 7]
arr > 5 checks every value and gives a row of True and False the same length as arr. That row is a mask. Put it in the square brackets and only the True cells come through. Read arr[arr > 5] as "the values of arr where this is True".
Combining conditions
mask = (arr > 2) & (arr < 8)
print(mask)
print(arr[mask])
print(arr[~mask])
print(arr[(arr < 2) | (arr > 8)])
[False True True False False False True True]
[5 3 4 7]
[1 8 2 9]
[1 9]
& means and, | means or, ~ flips a mask. Always keep the brackets around each condition.
The word and doesn't work here
print(arr[(arr > 2) and (arr < 8)])
Traceback (most recent call last):
File "S05L02_Indexing\and_keyword_error.py", line 5, in <module>
print(arr[(arr > 2) and (arr < 8)])
^^^^^^^^^^^^^^^^^^^^^^^
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
The keyword and wants one single True or False, and this mask has eight. The message suggests any() or all(), but that's not what you want when filtering. Swap and for & and or for |.
Masks on a grid
mat = np.array([[1, 2], [3, 4]])
print(mat > 2)
print(mat[mat > 2])
mat[mat > 2] = 0
print(mat)
[[False False]
[ True True]]
[3 4]
[[1 2]
[0 0]]
The mask has the same shape as the grid, but the picked values come out in one flat row, because True cells don't have to form a rectangle. A mask can write too: assigning to it replaces only those cells.
Picking by a list of positions
This is called fancy indexing. You pass a list of positions inside the brackets.
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60, 70, 80])
print(arr[[0, 3, 7]])
print(arr[[7, 0, 0]])
picked = arr[[0, 3, 7]]
picked[0] = 999
print(arr)
print(np.shares_memory(arr, picked))
[10 40 80]
[80 10 10]
[10 20 30 40 50 60 70 80]
False
The list decides the order and can repeat, which a slice can't do. And unlike a slice, fancy indexing gives you a copy, so arr doesn't change.
On a grid, one list picks whole rows, and two lists are read as (row, column) pairs:
arr = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print(arr[[0, 2]])
print(arr[[0, 2], [1, 3]])
[[ 1 2 3 4]
[ 9 10 11 12]]
[ 2 12]
Row 0 with column 1, and row 2 with column 3: two cells, not a block.
np.where, an if else for arrays
import numpy as np
arr = np.array([-3, 5, -1, 8, 0, -2, 7])
clean = np.where(arr > 0, arr, 0)
print(clean)
print(arr)
labels = np.where(arr >= 0, "pos", "neg")
print(labels)
[0 5 0 8 0 0 7]
[-3 5 -1 8 0 -2 7]
['neg' 'pos' 'neg' 'pos' 'pos' 'neg' 'pos']
Three arguments: condition, value if true, value if false. Where arr > 0, take the value from arr; elsewhere, use 0. It builds a new array, so arr doesn't change. The two values can be text too, and notice that 0 is labelled pos, because >= includes it.
An AI tool will happily write this line for you. Just be able to read it: condition, if true, if false.
np.where with one argument
idx = np.where(arr > 5)
print(idx)
print(arr[idx])
print(idx[0])
(array([3, 6]),)
[8 7]
[3 6]
With only the condition, np.where tells you where the matches are. It returns a tuple with one array per dimension. Use it as an index to get the values, or take idx[0] for just the positions.
Looping over an array
import numpy as np
arr = np.array([[1, 2], [3, 4]])
for row in arr:
print(row)
for value in arr.flat:
print(value)
for pos, value in np.ndenumerate(arr):
print(pos, value)
[1 2]
[3 4]
1
2
3
4
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
A for loop takes one step along the first dimension, so on a 2D array each step is a whole row. arr.flat walks every cell row by row, and np.ndenumerate gives you the position with each value. Loops are fine for looking at values. To filter or replace, reach for a mask or np.where first.
View or copy: the summary
| How you picked | Example | Memory |
|---|---|---|
| Slice | arr[1:4] | Shared with the original (a view) |
| Slice plus copy | arr[1:4].copy() | New |
| Boolean mask | arr[arr > 5] | New (a copy) |
| List of positions | arr[[0, 3, 7]] | New (a copy) |
| np.where, three arguments | np.where(arr > 0, arr, 0) | New |
If you can't remember, np.shares_memory will always tell you. Writing to a mask or a slice (arr[mask] = 0) always changes the original, because that's an assignment into it.
Try it yourself: take the array from where_replace.py and double only the values above zero, using a mask. Or ask an AI tool to write it, then read every line.
Previous: NumPy arrays, creation and dtypes. Next: reshaping, stacking and splitting arrays.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Supervised Learning: Features, Labels, Classification and Regression
What supervised learning is, shown on one small job: sorting support tickets into billing and technical. Rules vs learning from examples, classification vs regression, why some tickets stay hidden, and a 12-ticket classifier that labels three new ones.
NumPy and pandas for AI Engineers: Arrays for Vectors, Tables for Logs
NumPy and pandas at the depth an AI engineer needs. Shape, axis and broadcasting on 1,000 sample embeddings, a loop against one @, then a 2,000-row model call log: dtypes on load, missing values, filters, groupby model, merge and resample.
NumPy Arrays: Creation, Shape and Data Types From Scratch
Why a NumPy array beats a list for numbers, the seven ways to create one, what shape, ndim, size and dtype tell you, and why a slice is a view. Every output is from a real run on NumPy 2.
NumPy Shapes: reshape, transpose, stack, concatenate and split
Change the shape of a NumPy array without changing its data: reshape and -1, transpose, newaxis and squeeze, then stack, concatenate and split, with the errors you get when shapes don't fit.
