1
votes
import numpy as np
 
arr = np.array([[0, 1, 0],
                [1, 0, 0],
                [1, 0, 0]])
mask = arr
 
print('boolean mask is:')
print(mask)
print('arr[mask] is:')
print(arr[mask])

Result:

boolean mask is:
[[0 1 0]
 [1 0 0]
 [1 0 0]]
arr[mask] is:
[[[0 1 0]
  [1 0 0]
  [0 1 0]]

 [[1 0 0]
  [0 1 0]
  [0 1 0]]

 [[1 0 0]
  [0 1 0]
  [0 1 0]]]

I know how indexing works when the mask is 2-D, but confused when the mask is 3-D. Anyone can explain it?

1
Have you consulted the NumPy user guide/documentation?AMC
That's not a boolean mask. A boolean mask has booleans for the values, i.e. arr[mask == 1] or arr[mask.astype(bool)]alkasm

1 Answers

0
votes
import numpy as np

l = [[0,1,2],[3,5,4],[7,8,9]]

arr = np.array(l) 

mask = arr[:,:] > 5
print(mask) # shows boolean results
print(mask.sum()) # shows how many items are > 5
print(arr[:,1]) # slicing
print(arr[:,2]) # slicing 
print(arr[:, 0:3]) # slicing

output

[[False False False]
 [False False False]
 [ True  True  True]]
3
[1 5 8]
[2 4 9]
[[0 1 2]
 [3 5 4]
 [7 8 9]]