I have two ordered numpy arrays and I want to interleave them so that I take one item from the first array, then another from the second, then back to the first – taking the next item that is larger than the one I just took from the second and so on.
Those are actually arrays of indices to other arrays, and I’ll be ok with operating on the original arrays as long as the operation is vectorized (but of course working on the index array as a vector operation will be awesome).
Example (ok to assume that the intersection of arrays is empty)
a = array([1,2,3,4,7,8,9,10,17])
b = array([5,6,13,14,15,19,21,23])
I would like to get [1,5,7,13,17,19]
Vectorised solution (pedagogical style, easily understandable)
We can vectorise this by augmenting the arrays with a discriminator index, such that
ais tagged0andbis tagged1:Now, let’s combine and sort:
You can see that now the elements are in order but retaining their tags, so we can see which elements came from
aand fromb.So, let’s select the first element and each element where the tag changes from
0(fora) to1(forb) and back again:Efficient vectorised solution
You can do this slightly more efficiently by keeping the items and their tags in separate (but parallel) arrays:
This is slightly more efficient than the above solution; I get an average of 45 as opposed to 90 microseconds, although your conditions may vary.