python - comparison of two numpy arrays -


i've 2 numpy 2d arrays (say & b, sometime size equal or sometime not equal). need compare first column of both arrays , find index of elements occur in both arrays.

the below shown code gave me solution whenever both arrays have different size , elements of not present in b.

c=np.squeeze(a[np.array(np.where(np.in1d(a[:,0],b[:,1]))).t],axis=none)

but incorrect whenever elements of present in b.

can suggest solution ?

if , b following:

a=np.random.randint(0,5,(10,8)) b=np.random.randint(3,7,(10,8)) >>> array([[4, 4, 2, 1, 4, 3, 1, 2],        [1, 1, 1, 2, 0, 3, 0, 4],        [4, 3, 1, 1, 2, 1, 1, 3],        [3, 4, 3, 0, 3, 4, 2, 0],        [4, 1, 3, 0, 1, 4, 1, 2],        [1, 1, 1, 2, 2, 2, 0, 2],        [4, 3, 4, 2, 3, 2, 3, 2],        [4, 1, 4, 0, 3, 1, 2, 3],        [3, 2, 3, 2, 4, 4, 4, 2],        [0, 1, 4, 0, 2, 2, 1, 4]]) >>> b array([[4, 3, 5, 6, 4, 6, 3, 5],        [6, 3, 4, 4, 4, 6, 5, 4],        [5, 4, 5, 5, 5, 6, 3, 3],        [3, 5, 6, 5, 5, 5, 3, 6],        [5, 6, 5, 3, 5, 5, 5, 3],        [3, 3, 5, 3, 5, 6, 6, 3],        [6, 6, 6, 4, 6, 3, 4, 6],        [4, 4, 3, 5, 6, 6, 3, 3],        [5, 3, 4, 5, 3, 5, 5, 6],        [4, 3, 3, 6, 6, 4, 3, 4]]) 

you use intersect1d find values in both

np.intersect1d(a,b) array([3, 4]) 

and argwhere find indices of values in, example, column 0 of a:

[np.argwhere(x==a[:,0]) x in np.intersect1d(a,b)]  

returns

[array([[3],    [8]]), array([[0],    [2],    [4],    [6],    [7]])] 

Comments