1
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?

asked Aug 28, 2020 at 7:49
2
  • 1
    Have you consulted the NumPy user guide/documentation? Commented Aug 28, 2020 at 7:53
  • 2
    That's not a boolean mask. A boolean mask has booleans for the values, i.e. arr[mask == 1] or arr[mask.astype(bool)] Commented Aug 28, 2020 at 7:53

1 Answer 1

1
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]]
answered Aug 28, 2020 at 8:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.