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中更有效率地做到这一点?
您可以对 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)