Selecting rows from two nump.nd arrays and inserting 0 for missing match

I have two nd.numpy arrays named 'a' and 'b', I want to select only certain rows from 'b' array based on comparison with 'a' and insert 0 for rows if no match is found. I did the first part. eg,

a = np.array([[1,5,9],
           [2,6,10],
           [5,14,10]])

b = np.array([[ 1,0,9],
              [2,6,10],
              [4,6,10]])   

      

Output

[[ 1  0  9]
 [ 2  6 10]]

      

expected output

[[ 1  0  9]
 [ 2  6 10]
 [ 0  0  0]]

      

code:

import numpy as np
wanted= a[:,[0]]
y=b[np.logical_or.reduce([b[:,0] == x for x in wanted])]
print y

      

In the above example from array "a" on line "3" we don't have value "5" in array "b" so when comparing "a" with "b" if no match is found I want to insert '0' into the third string so that the dimensions of the two arrays are the same.

+3


source to share


1 answer


If you want any element b[:, 0]

that is not in a[:, 0]

to be zero, you can do the following:

>>> b[~np.in1d(b[:, 0], a[:, 0]), :] = 0
>>> b
array([[ 1,  0,  9],
       [ 2,  6, 10],
       [ 0,  0,  0]])

      



If you want any element b[:, 0]

that is not on the matching line a

to be zero:

>>> b[~np.any(b[:, 0][:,None]==a, axis=1), :] = 0
>>> b
array([[ 1,  0,  9],
       [ 2,  6, 10],
       [ 0,  0,  0]])

      

+1


source







All Articles