Search code examples
pythonarraysnumpysubtraction

Subtract 2 Numpy arrays with condition


I have two Numpy arrays which look like this:

a = [[ [1,2,3], [4,5,6] ], 
    [  [7,8,9], [10,11,12] ]]

b = [[ [1,1,1], [0,0,0] ], 
     [ [3,3,3], [4,4,4] ]]

I want to perform c = a - b with condition that c = 255 if b>0 else a

So c should be like this:

c = [[ [255,255,255], [4,5,6] ], 
     [ [255,255,255], [255,255,255] ]]

How to do it efficiently without any loop?


Solution

  • Use np.where

    >>> c = np.where(np.array(b)>0, 255, a)
    >>> c
    array([[[255, 255, 255],
            [  4,   5,   6]],
    
           [[255, 255, 255],
            [255, 255, 255]]])
    

    Btw. there is no subtracting happpening here; maybe change the title of your question.