Sub topic 10
Selecting row and column blocks with np.ix_
This chapter assumes you can create arrays with np.arange and reshape. It also assumes you know integer indexing and slicing, and you know that integer-array (fancy) indexing returns a copy. Those topics come from earlier chapters. Here you learn how to select a rectangular block of arbitrary rows and columns, which plain fancy indexing does not do directly.
The problem: two index arrays pair up
Suppose you want rows 0 and 2 of a matrix, and within those rows only columns 1 and 3. That is four elements arranged in a 2×2 block. The obvious attempt is wrong:
import numpy as np
a = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
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 two values in a 1-D array. You get the "diagonal" of the requested block, not the block itself.
What np.ix_ does
np.ix_ takes one 1-D sequence per axis and returns a tuple of reshaped index arrays. Each array has length 1 along every axis except its own. NumPy then broadcasts these arrays against each other, so every row index is combined with every column index.
import numpy as np
a = np.arange(12).reshape(3, 4)
ix = np.ix_([0, 2], [1, 3])
print(ix[0]) # [[0]
# [2]]
print(ix[1]) # [[1 3]]
print(ix[0].shape, ix[1].shape) # (2, 1) (1, 2)
print(a[ix]) # [[ 1 3]
# [ 9 11]]The row indices have shape (2, 1) and the column indices have shape (1, 2). Broadcasting stretches both to (2, 2). Position (i, j) of the result is a[rows[i], cols[j]]. The shape of the result is therefore (len(rows), len(cols)).
Equivalent ways to write the same selection
np.ix_ is a convenience. The same result comes from building the shapes yourself or from two selections in a row.
import numpy as np
a = np.arange(12).reshape(3, 4)
rows = np.array([0, 2])
cols = np.array([1, 3])
# 1. np.ix_
print(a[np.ix_(rows, cols)])
# 2. manual broadcasting
print(a[rows[:, np.newaxis], cols])
# 3. two steps: pick rows, then pick columns
print(a[rows][:, cols])All three print [[ 1 3] and [ 9 11]]. They differ in cost and in what they can do.
| Form | Intermediate array | Works for assignment | Notes |
|---|---|---|---|
| `a[np.ix_(rows, cols)]` | No | Yes | Clearest for N axes |
| `a[rows[:, None], cols]` | No | Yes | Same mechanism, written by hand |
| `a[rows][:, cols]` | Yes, a full copy of the selected rows | No | Assignment writes into a temporary copy |
The two-step form is the dangerous one. a[rows] is a copy, so a[rows][:, cols] = 0 modifies the temporary copy and leaves a unchanged. NumPy does not warn you in this case.
Order, repeats, and negative indices
The index sequences are used exactly as given. The result follows their order, and repeated indices produce repeated rows or columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[np.ix_([2, 0], [3, 1])])
# [[11 9]
# [ 3 1]]
print(a[np.ix_([0, 0], [1])])
# [[1]
# [1]]
print(a[np.ix_([-1, 0], [-1])])
# [[11]
# [ 3]]Reordering the lists reorders the output. Negative indices count from the end of their own axis, as in ordinary indexing. An index that is out of range for its axis raises IndexError.
The result is a copy
np.ix_ is a form of fancy indexing, so reading with it always returns a new array. Changing the result does not change the original.
import numpy as np
a = np.arange(12).reshape(3, 4)
block = a[np.ix_([0, 2], [1, 3])]
block[0, 0] = -1
print(a[0, 1]) # 1, unchanged
print(np.shares_memory(a, block)) # FalseThis differs from a slice such as a[0:3:2, 1:4:2]. That slice also selects a regular block, but it returns a view. If your rows and columns follow an arithmetic pattern, a slice avoids the copy. If they do not, for example rows 0, 2, and 5, you need np.ix_.
Assigning into a block
When a[np.ix_(...)] appears on the left side of an assignment, NumPy writes into a itself. No temporary copy is involved. The right side can be a scalar or any array that broadcasts to the block's shape.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[np.ix_([0, 2], [1, 3])] = 0
print(a)
# [[ 0 0 2 0]
# [ 4 5 6 7]
# [ 8 0 10 0]]
a[np.ix_([0, 2], [1, 3])] = [[10, 20], [30, 40]]
print(a)
# [[ 0 10 2 20]
# [ 4 5 6 7]
# [ 8 30 10 40]]Augmented assignment such as += also works. It behaves correctly as long as the indices in each list are unique.
Boolean sequences and ix_
np.ix_ also accepts 1-D boolean arrays. It converts each one to the integer positions where the value is True, so you can combine row and column conditions.
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]]The mask row_mask keeps rows 1 and 2, and col_mask keeps columns 1 and 3. The block holds every combination of those rows and columns.
Compare this with passing both masks straight into the brackets. NumPy then treats each mask as its nonzero() positions and pairs them, giving a 1-D result when the counts match, or an error when they differ. Here both masks have two True values, so a[row_mask, col_mask] would silently return [5 11] instead of a block. The np.ix_ wrapper is what makes it a block selection.
Because np.ix_ turns masks into positions immediately, it does not check that a mask has the same length as the axis it indexes. A mask that is too short selects positions from the start of the axis and gives no error. Build masks from the array being indexed, as above, so lengths match by construction.
More than two axes
np.ix_ takes one sequence per axis you want to index. For a 3-D array, pass three sequences and you get every combination across the three axes.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
block = b[np.ix_([0, 1], [0, 2], [1, 3])]
print(block.shape) # (2, 2, 2)
print(block)
# [[[ 1 3]
# [ 9 11]]
#
# [[13 15]
# [21 23]]]The element at block[i, j, k] equals b[i_list[i], j_list[j], k_list[k]]. If you want to take everything along one axis, pass np.arange of that axis length, or use a slice with ordinary indexing instead.
What np.ix_ cannot do
np.ix_ accepts only 1-D sequences. Slices, integers, Ellipsis, and multi-dimensional lists are not allowed. A 2-D input raises ValueError: Cross index must be 1 dimensional.
When you need a slice on one axis and a list on another, put them straight into the brackets. One integer array combined with slices behaves as you would expect, with no pairing involved.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[[0, 2], 1:3])
# [[ 1 2]
# [ 9 10]]
print(a[:, [3, 0]])
# [[ 3 0]
# [ 7 4]
# [11 8]]Pairing only happens when two or more arrays (or lists) appear in the same index. With one array plus slices, the array selects along its axis and the slices apply to the others. Later in this tutorial, the chapter on mixing index types covers cases where array positions and slices interact in less obvious ways.
An empty sequence is handled correctly: np.ix_ casts it to an integer index array, so you get an empty block instead of an error.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[np.ix_([], [1, 2])].shape) # (0, 2)Debugging checklist
When a block selection gives the wrong result, check these in order:
- Shape of the result. A 1-D result of length
nmeans the two index arrays were paired. Wrap them innp.ix_. - Unchanged original after assignment. Look for a chained selection such as
a[rows][:, cols] = .... Replace it with a singlea[np.ix_(rows, cols)] = .... - Unexpected rows or columns. Print the
np.ix_tuple and its shapes. They should be(len(rows), 1)and(1, len(cols)). - Mask lengths. Confirm each boolean mask comes from the matching axis of the same array.
- Accumulation with repeats. Switch from
+=tonp.add.at.
Exercise
Given m = np.arange(20).reshape(4, 5), write one expression that returns a 2×3 array containing rows 1 and 3 and columns 0, 2, and 4. Then write one statement that sets those same six elements to -1 in m. What does m[[1, 3], [0, 2, 4]] do instead?
Show answer
The selection is m[np.ix_([1, 3], [0, 2, 4])], which gives [[ 5 7 9] and [15 17 19]]. The assignment is m[np.ix_([1, 3], [0, 2, 4])] = -1. The expression m[[1, 3], [0, 2, 4]] raises IndexError because the two index lists have lengths 2 and 3 and cannot be paired. Shape mismatch errors like this are one sign you wanted np.ix_.
Exercise
Explain why a[[0, 2]][:, [1, 3]] = 0 leaves a unchanged, and give a correct one-line replacement.
Show answer
a[[0, 2]] uses fancy indexing, so it returns a copy of rows 0 and 2. The following [:, [1, 3]] = 0 assigns into that copy, and the copy is then discarded. The original array is never touched. The correct replacement is a[np.ix_([0, 2], [1, 3])] = 0, which performs a single indexed assignment directly on a.
Exercise
For a = np.arange(12).reshape(3, 4), use np.ix_ with boolean masks to select the block of rows whose first element is greater than 0 and columns whose first-row value is even. What is the result?
Show answer
rows = a[:, 0] > 0 gives [False, True, True], and cols = a[0, :] % 2 == 0 gives [True, False, True, False]. The expression a[np.ix_(rows, cols)] returns rows 1 and 2 at columns 0 and 2, which is [[ 4 6] and [ 8 10]].