0

I've come across numpy syntax I don't entirely understand. Here it is:

array[:, mask] = a

array is a numpy array of indeces, mask is a numpy array of bool values and a is an integer.

Could someone please translate this notation for me?

I couldn't find the answer anywhere online.

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • 1
    Does this answer your question? [How slicing in Python works](https://stackoverflow.com/questions/509211/how-slicing-in-python-works) – Rishi Jul 05 '23 at 11:08
  • The linked question "How slicing in Python works" is all about slicing in **native** Python data structures - it doesn't cover numpy specifics (like multiple axes, and the use of masks) – slothrop Jul 05 '23 at 11:52
  • For a numpy specific reference: https://numpy.org/doc/stable/user/basics.indexing.html#boolean-array-indexing. This is a subtopic in the `advanced indexing` section. In general the boolean mask is used the same as the `np.nonzero(mask)` indexing array. – hpaulj Jul 05 '23 at 14:58

2 Answers2

2

Translation:

  • in the array array
  • for the rows [:] (all in this case)
  • do for every column where mask contains True
  • the operation: assign a

So it writes a into all matrix cells there masks contains a True value.

here is an example:

import numpy as np

array = np.array([
    [1,5,3],
    [1,5,3],
    [1,5,3],
])
mask = np.array(
    [True,False,True]
)
array[:, mask] = 10
print(array)

results in:

[[10  5 10]
 [10  5 10]
 [10  5 10]]
Cube
  • 205
  • 1
  • 7
0

For a more detailed answer on slicing, refer to this How slicing in Python works. A mask can be used instead of an explicit range to select specific indices. Coming back to your question, it will select all the rows and only those columns where the value of the mask is true, so all those cells will be replaced with integer a.

Rishi
  • 28
  • 1
  • 6
  • The linked question is all about slicing in native Python data structures - it doesn't cover numpy specifics (like multiple axes, and the use of masks) – slothrop Jul 05 '23 at 11:52