是否可以删除此函数中的 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/