1

How can I mask two NumPy arrays properly? I want find pe values that are not equal to 255, for example. I also want my desired output array be the same size aspd and pe, i.e., (7, 7) and filled with 0's.
What is the most efficient way to achieve this?

import numpy as np

pd = np.random.randint(254,256, size=(7,7))
pe = np.random.randint(0,7, size=(7,7))

Desired output

[[6 6 0 0 6 6 1]
 [2 6 1 1 5 6 3]
 [3 4 6 6 3 5 6]
 [3 5 0 3 2 0 0]
 [0 3 6 1 3 6 1]
 [6 3 4 1 0 3 1]
 [6 0 4 2 2 6 4]]

Many thanks

7
  • 1
    So for each index in the output array, you'd like pe[index] if pd[index] != 255 else 0, right? Commented Jun 6, 2022 at 12:35
  • 2
    pe * (pd == 255), IIUC. Assuming you meant that are not equal to 255 in pd Commented Jun 6, 2022 at 12:36
  • 1
    Which is slightly faster than np.where(pd == 255, 0, pe) which I was going to propose. Kudos! :) Commented Jun 6, 2022 at 12:38
  • Hi Dominik. Yes, that's correct. Commented Jun 6, 2022 at 12:40
  • 4
    Note that we optimized significantly np.where in the very last version (1.23) of Numpy so np.where(pd == 255, 0, pe) may now be faster than pe * (pd == 255) or at least close to that. Commented Jun 6, 2022 at 13:42

1 Answer 1

1

Logical indexing seems the simplest of all options.

import numpy as np

pd = np.random.randint(254,256, size=(7,7))
pe = np.random.randint(0,7, size=(7,7))

pe[pd == 255] = 0

[[3 6 0 2 0 0 0]
 [0 3 4 5 2 0 5]
 [0 0 6 0 1 0 5]
 [0 3 0 4 0 6 0]
 [2 0 0 0 0 0 0]
 [2 0 4 0 0 0 5]
 [0 0 3 0 2 4 0]]

Based on your data size, you may try other options:

pe = np.where(pd == 255, 0, pe)
# OR
pe = pe * (pd == 255)

but I guess indexing is still simple and fast.

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks for a clear reply, AboAmmar!

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.