0

I'm dealing with a large N-D numpy array. I would like to keep only those elements present in a different numpy array, and set the remaining values to 0.

for example, if we consider this numpy array

array([[[36,  1, 72],
        [76, 50, 23],
        [28, 68, 17],
        [84, 75, 69]],

       [[ 5, 15, 93],
        [92, 92, 88],
        [11, 54, 21],
        [87, 76, 81]]])

and I want to set 0 in all places except where the values are 50, 11, 72

3
  • What have you tried so far? Commented Dec 2, 2020 at 8:53
  • @MadPhysicist, i took the simple approach of iterating over the list and setting replacing the value to zero, and I was sure that it was not the best approach Commented Dec 2, 2020 at 8:59
  • There's no list here. Terminology is important, as is providing an example of your work. Commented Dec 2, 2020 at 12:58

2 Answers 2

3

If you are onto using only numpy, this can also be done using simple use of broadcasting by casting the vals array to just one rank higher than a. This is accomplished without using iterations or other functionalities.

import numpy as np

a = np.array([[[36,  1, 72],
         [76, 50, 23],
         [28, 68, 17],
         [84, 75, 69]],
 
        [[ 5, 15, 93],
         [92, 92, 88],
         [11, 54, 21],
         [87, 76, 81]]])

vals = np.array([50, 11, 72])
inds = a == vals[:, None, None, None]
a[~np.any(inds, axis = 0)] = 0
a

Output:

array([[[ 0,  0, 72],
        [ 0, 50,  0],
        [ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 0,  0,  0],
        [ 0,  0,  0],
        [11,  0,  0],
        [ 0,  0,  0]]])
Sign up to request clarification or add additional context in comments.

Comments

1

I set up a mask by combining reduce with np.logical_or and iterated over the values that should remain:

import functools
import numpy as np

arr = np.array([[[36,  1, 72],
        [76, 50, 23],
        [28, 68, 17],
        [84, 75, 69]],
       [[ 5, 15, 93],
        [92, 92, 88],
        [11, 54, 21],
        [87, 76, 81]]])

# Set the values that should not
# be set to zero
vals = [11, 50, 72]

# Create a mask by looping over the above values
mask = functools.reduce(np.logical_or, (arr==val for val in vals))

masked = np.where(mask, arr, 0.)

print(masked)
> array([[[ 0.,  0., 72.],
        [ 0., 50.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [11.,  0.,  0.],
        [ 0.,  0.,  0.]]])

Comments

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.