@Divakar 提供的解决方案非常适合整数数据,但要注意浮点值的精度问题,尤其是当它们跨越多个数量级时(例如 [[1.0, 2,0, 3.0, 1.0e+20],...])。在某些情况下,r 可能太大,以至于应用a+r 和b+r 会消除您尝试运行searchsorted 的原始值,而您只是将r 与r 进行比较。
为了使该方法对浮点数据更加稳健,您可以将行信息作为值的一部分(作为结构化 dtype)嵌入到数组中,然后对这些结构化 dtype 运行 searchsorted。
def searchsorted_2d (a, v, side='left', sorter=None):
import numpy as np
# Make sure a and v are numpy arrays.
a = np.asarray(a)
v = np.asarray(v)
# Augment a with row id
ai = np.empty(a.shape,dtype=[('row',int),('value',a.dtype)])
ai['row'] = np.arange(a.shape[0]).reshape(-1,1)
ai['value'] = a
# Augment v with row id
vi = np.empty(v.shape,dtype=[('row',int),('value',v.dtype)])
vi['row'] = np.arange(v.shape[0]).reshape(-1,1)
vi['value'] = v
# Perform searchsorted on augmented array.
# The row information is embedded in the values, so only the equivalent rows
# between a and v are considered.
result = np.searchsorted(ai.flatten(),vi.flatten(), side=side, sorter=sorter)
# Restore the original shape, decode the searchsorted indices so they apply to the original data.
result = result.reshape(vi.shape) - vi['row']*a.shape[1]
return result
编辑:这种方法的时机太糟糕了!
In [21]: %timeit searchsorted_2d(a,b)
10 loops, best of 3: 92.5 ms per loop
你最好只在数组上使用map:
In [22]: %timeit np.array(list(map(np.searchsorted,a,b)))
100 loops, best of 3: 13.8 ms per loop
对于整数数据,@Divakar 的方法仍然是最快的:
In [23]: %timeit searchsorted2d(a,b)
100 loops, best of 3: 7.26 ms per loop