1

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?

1
  • 1
    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. Commented Jan 14, 2019 at 4:27

1 Answer 1

3

You could use argwhere:

rows = np.argwhere(a[:, 3] == 0)    
cols = [2, 3, 4]        

b[rows, cols] = 2       # Replace the values with 2
print(b)

Output

[[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.]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.