I have this numpy array where the values in each row will always be sorted and monotonically increasing:
a = np.array([[1, 2, 3, 4, 8],
[2, 5, 6, 7, 8],
[5, 7, 11, 12, 13]])
and I want to search for the following values (which are NOT sorted or monotonic) for each row:
b = np.array([4.5, 2.3, 11.6])
so that I get an answer of:
[4, 1, 3]
However, searchsorted does not support this (it feels like it needs an axis
keyword).
Is there an EFFICIENT way I can do this for a very large array? Obviously with a for
loop I can index the array a
and b
like this:
for i in np.arange(np.alen(a)):
print a[i].searchsorted(b[i])
but this is slow when a
is large.
Is there a way to do this in numpy that is more efficient?
You can searchsorted on the ravel/flattened array:
In [11]: np.searchsorted(a.ravel(), b)
Out[11]: array([3, 6])
You can then use divmod on the result (which gets the row and column):
In [12]: divmod(np.searchsorted(a.ravel(), b), a.shape[1])
Out[12]: (array([0, 1]), array([3, 1]))
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