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

Time:10-14

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.

CodePudding user response:

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])

CodePudding user response:

It looks like you can use the bitwise or operator here. Something like

for i in range(len(y2_a)):
    y2_a[i] = y1_a[i] | y2_a[i]

This will keep the ones that are already in y2_a and flip the 0s in y2_a if there is a 1 in that position in y1_a

CodePudding user response:

You can use:

out = y1_a | y2_a

output:

array([1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1])
  • Related