amito
amito

Reputation: 11

Multiple array manipulation in Numpy

A= [[4,0,1], [8,0,1]]

B = [[4,1,1], [8,0,1]]

Output= [[4,0,1], [8,0,1]]

I have 2 numpy arrays A and B and I want to get an output nparray which is like an XOR of the values in the 2 original array i.e. if the cells are same, keep the value, if they are different, put a 0 there. What is the best way to do this? Thank You in advance.

Upvotes: 1

Views: 58

Answers (2)

hpaulj
hpaulj

Reputation: 231385

While where is a nice one-liner, you should learn how to do this with simple boolean masking.

In [9]: A= np.array([[4,0,1], [8,0,1]])
In [10]: B =np.array( [[4,1,1], [8,0,1]])

A boolean array showing where the elements don't match

In [11]: A!=B
Out[11]: 
array([[False,  True, False],
       [False, False, False]], dtype=bool)

Use that to modify a copy of A:

In [12]: C=A.copy()
In [13]: C[A!=B]=0
In [14]: C
Out[14]: 
array([[4, 0, 1],
       [8, 0, 1]])

For clarity, let's insert a different value, -1:

In [15]: C[A!=B]=-1
In [16]: C
Out[16]: 
array([[ 4, -1,  1],
       [ 8,  0,  1]])

Upvotes: 2

Divakar
Divakar

Reputation: 221564

np.where might be a good fit here -

np.where(A == B,A,0)

Basically with the three input format : np.where(mask,array1,array2), it selects elements from array1 or array2 if the corresponding elements in the mask are True or False respectively. So, in our case with np.where(A == B,A,0), the mask A==B when True selects elements from A, which would be the same as B, otherwise sets to 0.

The same effect could also be brought in with elementwise multiplication between the mask A==B and A, like so -

A*(A==B)

Sample run -

In [24]: A
Out[24]: 
array([[4, 5, 1],
       [8, 0, 1]])

In [25]: B
Out[25]: 
array([[4, 1, 1],
       [8, 0, 1]])

In [26]: np.where(A == B,A,0)
Out[26]: 
array([[4, 0, 1],
       [8, 0, 1]])

In [27]: A*(A==B)
Out[27]: 
array([[4, 0, 1],
       [8, 0, 1]])

Upvotes: 2

Related Questions