python-3.x - 在另一个数组中高效查找下一个更大的

标签 python-3.x numpy

是否可以删除此函数中的 for 循环并加快处理速度?对于此函数,我无法使用矢量方法获得相同的结果。或者有其他选择吗?

import numpy as np

indices = np.array(
    [814, 935, 1057, 3069, 3305, 3800, 4093, 4162, 4449])

within = np.array(
    [193, 207, 243, 251, 273, 286, 405, 427, 696,
     770, 883, 896, 1004, 2014, 2032, 2033, 2046, 2066,
     2079, 2154, 2155, 2156, 2157, 2158, 2159, 2163, 2165,
     2166, 2167, 2183, 2184, 2208, 2210, 2212, 2213, 2221,
     2222, 2223, 2225, 2226, 2227, 2281, 2282, 2338, 2401,
     2611, 2612, 2639, 2640, 2649, 2700, 2775, 2776, 2785,
     3030, 3171, 3191, 3406, 3427, 3527, 3984, 3996, 3997,
     4024, 4323, 4331, 4332])


def get_first_ind_after(indices, within):
    """returns array of the first index after each listed in indices

    indices and within must be sorted ascending
    """
    first_after_leading = []
    for index in indices:

        for w_ind in within:

            if w_ind > index:
                first_after_leading.append(w_ind)

                break

    # convert to np array
    first_after_leading = np.array(first_after_leading).flatten()

    return np.unique(first_after_leading)

它应该为索引数组中的每个返回下一个最大的数字(如果有的话)。

# Output:
[ 883 1004 2014 3171 3406 3984 4323]

最佳答案

这是一个基于 np.searchsorted 的 -

def next_greater(indices, within):
    idx = np.searchsorted(within, indices)
    idxv = idx[idx<len(within)]
    idxv_unq = np.unique(idxv)
    return within[idxv_unq]

或者,idxv_unq 可以像这样计算并且应该更有效 -

idxv_unq = idxv[np.r_[True,idxv[:-1] != idxv[1:]]]

关于python-3.x - 在另一个数组中高效查找下一个更大的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56466967/

相关文章:

python - 魔法 python 不工作

python - 如何从 python 中的矩阵的每一列中选择具有最多最小值的行?

python - 给定返回 n 维数组的函数,如何创建 n+1 维数组

python - Numpy 和 Ndarray 的外积

python - 检查 2 列表中有多少值相等

python - 在 python 中将带有 NaN 的 Numpy 数组写入 CSV

python - brew install opencv3 显然成功,但缺少 cv2.so 和 cv2.py

python - 如何在一个函数中设置两个消息处理程序

python - 拉普拉斯语的opencv失败并显示cv2。错误:OpenCV(4.1.2)

python - 如何在 numPy 中执行此操作?