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
CodePudding user response:
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.
