Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align numpy array according to another array

I have a numpy array a containing arbitrary integer numbers, and I have another array b, (it is always a subset of a, but the order of numbers in b is different than a. I want to align the elements of b in the order it appears in a.

a = np.array([4,2,6,5,8,7,10,12]);
b = np.array([10,6,2,12]),

I want b to be align as [2,6,10,12]. How can I do it in numpy efficiently ?

like image 762
Shew Avatar asked Jan 29 '17 17:01

Shew


1 Answers

Approach #1 : One approach with np.in1d, assuming no duplicates in a -

a[np.in1d(a,b)]

Better sample case with elements in a disturbed such that its not sorted for the common elements to present a variety case -

In [103]: a
Out[103]: array([ 4, 12,  6,  5,  8,  7, 10,  2])

In [104]: b
Out[104]: array([10,  6,  2, 12])

In [105]: a[np.in1d(a,b)]
Out[105]: array([12,  6, 10,  2])

Approach #2 : One approach with np.searchsorted -

sidx = a.argsort()
out = a[np.sort(sidx[np.searchsorted(a,b,sorter=sidx)])]
like image 136
Divakar Avatar answered Oct 03 '22 09:10

Divakar