python - 如何在二维数组中使用 numpy.searchsorted 进行矢量化

标签 python arrays performance numpy search

我有一个用于查找的二维数组 (a) 和一个用于查找应插入元素的索引的数组 (v):

import numpy as np

# [EDIT] Add more records which contain NaNs
a = np.array(
[[0., 923.9943, 996.8978, 1063.9064, 1125.639, 1184.3985, 1259.9854, 1339.6107, 1503.4462, 2035.6527],
 [0., 1593.6196, 1885.2442, 2152.956, 2419.0038, 2843.517, 3551.225, 5423.009, 18930.8694, 70472.4002],
 [0., 1593.6196, 1885.2442, 2152.956, 2419.0038, 2843.517, 3551.225, 5423.009, 18930.8694, 70472.4002],
 [0., 1084.8388, 1132.6918, 1172.2278, 1215.7986, 1259.062, 1334.4778, 1430.738, 1650.4502, 3966.1578],
 [0., 1084.8388, 1132.6918, 1172.2278, 1215.7986, 1259.062, 1334.4778, 1430.738, 1650.4502, 3966.1578],
 [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
 [0., 923.9943, 996.8978, 1063.9064, 1125.639, 1184.3985, 1259.9854, 1339.6107, 1503.4462, 2035.6527],
 [0., 1593.6196, 1885.2442, 2152.956, 2419.0038, 2843.517, 3551.225, 5423.009, 18930.8694, 70472.4002],
 [0., 1593.6196, 1885.2442, 2152.956, 2419.0038, 2843.517, 3551.225, 5423.009, 18930.8694, 70472.4002],
 [0., 1084.8388, 1132.6918, 1172.2278, 1215.7986, 1259.062, 1334.4778, 1430.738, 1650.4502, 3966.1578],
 [0., 1084.8388, 1132.6918, 1172.2278, 1215.7986, 1259.062, 1334.4778, 1430.738, 1650.4502, 3966.1578]])

v = np.array([641.954, 56554.498, 168078.307, 1331.692, 2233.327, 1120.03, 641.954, 56554.498, 168078.307, 1331.692, 2233.327])

这是我想要得到的结果:

[1, 9, 10, 6, 9, 0, 1, 9, 10, 6, 9]

显然,使用 for 循环我可以像这样索引数组 a 和 v:

for i, _ in enumerate(a):
    print(np.searchsorted(a[i], v[i]))

是否有更有效的矢量化方法来做到这一点?

最佳答案

灵感来自 Vectorized searchsorted numpy对于基本思想,这是 2D1D 数组之间的一个 -

def searchsorted2d(a,b):
    # Inputs : a is (m,n) 2D array and b is (m,) 1D array.
    # Finds np.searchsorted(a[i], b[i])) in a vectorized way by
    # scaling/offsetting both inputs and then using searchsorted

    # Get scaling offset and then scale inputs
    s = np.r_[0,(np.maximum(a.max(1)-a.min(1)+1,b)+1).cumsum()[:-1]]
    a_scaled = (a+s[:,None]).ravel()
    b_scaled = b+s

    # Use searchsorted on scaled ones and then subtract offsets
    return np.searchsorted(a_scaled,b_scaled)-np.arange(len(s))*a.shape[1]

给定样本的输出-

In [101]: searchsorted2d(a,v)
Out[101]: array([ 1,  9, 10,  6,  9])

所有 NaN 行的情况

要扩展以使其适用于所有 NaN 行,我们需要更多步骤 -

valid_mask = ~np.isnan(a).any(1)
out = np.zeros(len(a), dtype=int)
out[valid_mask] = searchsorted2d(a[valid_mask],v[valid_mask])

关于python - 如何在二维数组中使用 numpy.searchsorted 进行矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56471109/

相关文章:

python正则表达式向前看正+负

Javascript - 多维关联数组

ruby - 在 Ruby 中,获取数组中最大值索引的最简洁方法是什么?

javascript - Bluebird promisify vs promisifyAll 想要从模块中 promise 一种方法时的性能比较

c# - 为什么这个简单的 F# 代码比 C#/C++ 版本慢 36 倍?

c++ - Windows 安全模式运行简单程序(至少)快 3 倍?

python - 正则表达式多重表达式

python - Django:不允许用户在未登录时查看页面

params 中 param 的 python 语法

PHP多维数组相交