Search code examples
pythonarraysnumpyarraylistnumpy-ndarray

Changing the elements of one array with respect to the other in Python


I have two arrays as shown below.

import numpy as np
y1 = [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1]
y2 = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1]
y1_a = np.array(y1)
y2_a = np.array(y2)
print(y1_a)
print(y2_a)

I have to modify 'y2_a' array under this condition:

Whenever 'y1_a' is 1 in a given array position and if 'y2_a' is 0 in that same array position, then I have to replace 'y2_a' with 1. I do not want to do this for the 0 values in 'y1_a'.

I have to write this modified array to another array variable.


Solution

  • You can use numpy.where.

    # Whenever 'y1_a==1' and  'y2_a==0', we set '1' 
    # for other conditions we set 'y2_a'.
    res = np.where(y1_a & ~y2_a, 1, y2_a)
    print(res)
    

    Output: array([1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1])