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 ?
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)])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With