I want to change some values in a numpy 2D array, based on the values of another array. The rows of the submatrix are selected using boolean slicing and the columns are selected by using integer slicing.
Here is some example code:
import numpy as np
a = np.array([
[0, 0, 1, 0, 0],
[1, 1, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 1, 1, 0, 0],
[1, 0, 0, 0, 1],
[0, 0, 0, 0, 0],
])
b = np.ones(a.shape) # Fill with ones
rows = a[:, 3] == 0 # Select all the rows where the value at the 4th column equals 0
cols = [2, 3, 4] # Select the columns 2, 3 and 4
b[rows, cols] = 2 # Replace the values with 2
print(b)
The result I want in b is:
[[1. 1. 2. 2. 2.]
[1. 1. 2. 2. 2.]
[1. 1. 1. 1. 1.]
[1. 1. 2. 2. 2.]
[1. 1. 2. 2. 2.]
[1. 1. 2. 2. 2.]]
But, the only thing I get is an exception:
IndexError
shape mismatch: indexing arrays could not be broadcast together with shapes (5,) (3,)
How could I achieve the result I want?
np.ix_can convert the boolean into the correct index,b[np.ix_(rows, cols)]. The end result is the same pair of indexing arrays that the answers provide - a (5,1) and (1,3) which broadcast together to index a (5,3) block.