Sub topic 10
Selecting row and column blocks with np.ix_
This chapter assumes you know integer indexing, slicing, and basic fancy indexing (selecting with a list or array of integers). You should also know that fancy indexing returns a copy. Here you will learn how to pick a block from an array when the rows and columns you want are not contiguous.
The problem: index arrays pair up
Suppose you want rows 0 and 2 and columns 1 and 3 of a 3×4 array, which gives a 2×2 block. The obvious attempt does something else.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[[0, 2], [1, 3]]) # [ 1 11]NumPy pairs the two index arrays element by element. It returns a[0, 1] and a[2, 3], which is a 1-D array of two values. You asked for four values.
How np.ix_ builds a block
np.ix_ takes one sequence per axis and returns index arrays that have different shapes. Those shapes make NumPy combine every row with every column through broadcasting.
import numpy as np
a = np.arange(12).reshape(3, 4)
rows = [0, 2]
cols = [1, 3]
r, c = np.ix_(rows, cols)
print(r) # [[0]
# [2]]
print(c) # [[1 3]]
print(r.shape, c.shape) # (2, 1) (1, 2)
print(a[r, c]) # [[ 1 3]
# [ 9 11]]
print(a[np.ix_(rows, cols)]) # same resultThe column vector r has shape (2, 1) and the row vector c has shape (1, 2). Broadcasting stretches them to (2, 2). The result then contains the position (rows[i], cols[j]) at output position [i, j].
Equivalent forms
You can get the same block without np.ix_ by adding an axis yourself, or by indexing in two steps.
import numpy as np
a = np.arange(12).reshape(3, 4)
rows = np.array([0, 2])
cols = np.array([1, 3])
print(a[rows[:, np.newaxis], cols]) # [[ 1 3]
# [ 9 11]]
print(a[rows][:, cols]) # [[ 1 3]
# [ 9 11]]The two-step form is easy to read, but it builds an intermediate copy of the selected rows. Use it only for reading, as the next section shows.
Assigning to a block
np.ix_ works on the left side of an assignment. This is the main reason to prefer it over chaining.
import numpy as np
a = np.arange(12).reshape(3, 4)
rows = [0, 2]
cols = [1, 3]
a[np.ix_(rows, cols)] = 0
print(a)
# [[ 0 0 2 0]
# [ 4 5 6 7]
# [ 8 0 10 0]]
b = np.arange(12).reshape(3, 4)
b[rows][:, cols] = 0 # modifies a temporary copy
print(b[0, 1]) # 1, so b is unchangedIn the chained form, b[rows] is fancy indexing and returns a copy. The assignment then writes into that copy, which is thrown away. NumPy gives no error, so the bug is silent.
Boolean sequences
np.ix_ also accepts boolean arrays. It converts each one to the integer positions where the value is True.
import numpy as np
a = np.arange(12).reshape(3, 4)
row_mask = a[:, 0] > 0 # [False True True]
col_mask = a[0] % 2 == 1 # [False True False True]
print(a[np.ix_(row_mask, col_mask)]) # [[ 5 7]
# [ 9 11]]This is how you keep rows that pass one test and columns that pass another. A full-shape mask like a[a % 2 == 0] cannot do this, because it flattens the result.
Things to remember
- The result is always a copy, never a view, because
np.ix_produces integer-array indexing. - Each sequence you pass must match one axis of the array, in order. For a 2-D array you pass exactly two.
- The block follows the order you give.
np.ix_([2, 0], [3, 1])reverses both axes of the selection. - If your rows or columns form a regular range, a slice is simpler and returns a view.
Exercise
Given a = np.arange(20).reshape(4, 5), write one expression that sets rows 1 and 3, columns 0, 2, and 4 to -1. Then explain why a[[1, 3]][:, [0, 2, 4]] = -1 would not work.
Show answer
Use a[np.ix_([1, 3], [0, 2, 4])] = -1. The chained form fails because a[[1, 3]] is fancy indexing, which returns a copy. The second index and the assignment then act on that copy, so a never changes.