Search code examples
pythonlistnumpyboolean

How to create a Boolean array with the same shape of a list containing multiple arrays


I have a list that contains multiple same size arrays. I would like to create a 0-1 array with the same shape where every element in the list that is equal to a user-define value should be set as 0 in the 0-1 array.

import numpy as np

y = ([np.array([[1., 0., 0.],
        [0., 0., 1.],
        [0., 0., 1.]], dtype='float32'),
   np.array([[0., 0., 1.],
        [0., 0., 1.],
        [1., 0., 0.]], dtype='float32'),
   np.array([[   0.,    0.,    1.],
        [   1.,    0.,    0.],
        [-100., -100., -100.]], dtype='float32')])

x = np.ones_like(y)
x[y == -100.] = 0
print(x)

array([[[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]],

       [[1., 1., 1.],
        [1., 1., 1.],
        [1., 1., 1.]]], dtype=float32)

With the current version, every element in x is set as 1. If I use concatenate for y, it works, but then it is no longer the same shape.


Solution

  • You're super close. This would work if y was itself an np.ndarray:

    y = np.asarray(y)
    
    x = 1 - (y == -100.)
    print(x)
    
    array([[[1, 1, 1],
            [1, 1, 1],
            [1, 1, 1]],
    
           [[1, 1, 1],
            [1, 1, 1],
            [1, 1, 1]],
    
           [[1, 1, 1],
            [1, 1, 1],
            [0, 0, 0]]])
    

    By not making y here an np.ndarray, your expression y == -100. doesn't do what you think it's doing. It's comparing the entire object to -100, not elementwise. If you run just that expression, you end up getting just False, which is not what you were probably hoping for.