如何使用 numpy 实现查找表操作



假设我有这样的地图:

{-1: -1, 1: 255, 2: 255, 7: 0, 8:1, ...}

我有一个数组m.m的值是映射的键,我想将数组的值从映射键转换为映射值。我怎么能用opencvnumpy做到这一点?

NumPy 解决方案是:

def numpy_map(arr, d):
    v = np.array(list(d.values()))
    k = np.array(list(d.keys()))    
    sidx = k.argsort()
    return v[sidx[np.searchsorted(k, arr, sorter=sidx)]]
print(numpy_map(<here you put the numpy array>, <here you put the dictionary>))

虽然使用一些pandas会更容易,而且是最佳的:

print(pd.Series(<here you put the numpy array>).map(<here you put the dictionary>).values)

最新更新