Search code examples
pythonarraysnumpylist-comprehension

Multiple actions for multiple arrays in list comprehension


I would like to substitute the '1's on an array nparray1 = np.array([1, 1, 0, 0, 1]) by the values on another array nparray2 = np.array([8,7,4]), to produce nparray1 = np.array([8, 7, 0, 0, 4]).

I was hoping to do this as efficiently as possible, hence I thought using a list comprehension would be the best alternative, however, I am unable to find a way to do this. The alternative for loop would look like:

nparray1 = np.array([1, 1, 0, 0, 1])
nparray2 = np.array([8,7,4])

for i in range(len(nparray1)):
    if nparray1[i]==True:
        nparray1[i] = nparray2[0]
        nparray2    = nparray2[1:]

Solution

  • You can use:

    nparray1[nparray1 == 1] = nparray2
    print(nparray1)
    
    # Output
    array([8, 7, 0, 0, 4])