Numpy.searchsorted with 2D Array

I have this numpy array, where the values ​​in each row will always be sorted and monotonically increase:

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 monotonous) for each row:

b = np.array([4.5, 2.3, 11.6])

to get an answer:

[4, 1, 3]

However, searchsorted does not support this (it looks like it needs a keyword axis).

Is there an EFFECTIVE way to do this for a very large array? It is obvious that with the cycle forI can index the array aand bas follows:

for i in np.arange(np.alen(a)):
     print a[i].searchsorted(b[i])

but it is a slow time when agreat.

Is there a way to do this in numpy that is more efficient?

+4
1

ravel/flattened:

In [11]: np.searchsorted(a.ravel(), b)
Out[11]: array([3, 6])

divmod ( ):

In [12]: divmod(np.searchsorted(a.ravel(), b), a.shape[1])
Out[12]: (array([0, 1]), array([3, 1]))
+2

Source: https://habr.com/ru/post/1532874/


All Articles