numpy.searchsorted与2D数组

ccb*_*ney 10 python arrays search numpy

我有这个numpy数组,其中每行中的值将始终排序并单调增加:

a = np.array([[1, 2, 3, 4, 8],
       [2, 5, 6, 7, 8],
       [5, 7, 11, 12, 13]])
Run Code Online (Sandbox Code Playgroud)

我想为每一行搜索以下值(未排序或单调):

b = np.array([4.5, 2.3, 11.6])
Run Code Online (Sandbox Code Playgroud)

这样我得到了答案:

[4, 1, 3]
Run Code Online (Sandbox Code Playgroud)

但是,searchsorted不支持这种情况(感觉它需要一个axis关键字).

对于一个非常大的阵列,我是否有一种有效的方法可以做到这一点?显然有一个for循环我可以索引数组a,b像这样:

for i in np.arange(np.alen(a)):
     print a[i].searchsorted(b[i])
Run Code Online (Sandbox Code Playgroud)

但是当a它很大时这很慢.

有没有办法在numpy中更有效率地做到这一点?

And*_*den 2

您可以对 ravel/flattened 数组进行搜索排序:

In [11]: np.searchsorted(a.ravel(), b)
Out[11]: array([3, 6])
Run Code Online (Sandbox Code Playgroud)

然后,您可以对结果使用 divmod (获取行和列):

In [12]: divmod(np.searchsorted(a.ravel(), b), a.shape[1])
Out[12]: (array([0, 1]), array([3, 1]))
Run Code Online (Sandbox Code Playgroud)

  • 这要求每一行都具有比任何前一行更大的值,这是OP示例的情况,但对于一般数组来说似乎是一个强有力的条件。 (7认同)
  • @KernowBunney 啊,好吧,所以更有效,但类似于“np.diag(np.apply_along_axis(np.searchsorted, 1, a, b))”。对于 for 循环的性能来说,使用 cython 是一个简单的选择。 (6认同)