3

I have two numpy arrays:

a = np.arange(100*100).reshape(100,100)
b = np.random.rand(100, 100)

I also have a tuple of slices to extract a certain piece of the array:

slice_ = (slice(5, 10), slice(5, 10))

I then have a set of boolean indices to select a certain part of this slice:

indices = b[slice_] > 0.5

If I want to set these indices to a different value I can do it easily:

a[slice_][indices] = 42

However, if I create another set of boolean indices to select a specific part of the indexed array:

high_indices = a[slice_][indices] > 700

and then try and set the value of the array at these indices:

a[slice_][indices][high_indices] = 42 # Doesn't do anything!

I thought maybe I needed to AND the two index arrays together, but they are different shape: indices has a shape of (5, 5) and high_indices has a shape of (12,).

I think I've got myself into a terrible muddle here trying to do something relatively simple. How can I index using these two boolean arrays in such a way that I can set the values of the array?

robintw
  • 27,571
  • 51
  • 138
  • 205

1 Answers1

5

Slicing a numpy array returns a view, but boolean indexing returns a copy of an array. So when you indexed it first time with boolean index in a[slice_][indices][high_indices], you got back a copy, and the value 42 is assigned to a copy and not to the array a. You can solve the problem by chaining the boolean index:

a[slice_][(a[slice_] > 700) & (b[slice_] > 0.5)] = 42
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85