[英]MATCH smallest value equivalent code in python
I would like to seek the quickest equivalent Python code of the MATCH Excel function which returns the position of the smallest and nearest value of "VALUE" in a "RANGE", ie Match(VALUE, RANGE, -1). I would like to seek the quickest equivalent Python code of the MATCH Excel function which returns the position of the smallest and nearest value of "VALUE" in a "RANGE", ie Match(VALUE, RANGE, -1). This function should be applied to multiple "VALUE", ie, a vector.这个 function 应该应用于多个“VALUE”,即一个向量。
I have an initial solution below but it is very very slow with a high number of element (100k):我在下面有一个初始解决方案,但是对于大量元素(100k)来说它非常慢:
In the example below I want to match each value in "vector" to find the position of its smallest nearest value in the "vector_to_match":在下面的示例中,我想匹配“vector”中的每个值以在“vector_to_match”中找到其最小最近值的 position:
import numpy as np
import perfplot
simulLength = 100000
vector = np.random.rand(simulLength)
vector_to_match = np.arange(100000)/100000
def Match_Smallest(x):
orderCheck = np.array((vector_to_match < x) * 1)
x_order = sum(orderCheck) - 1
return x_order
def A_Finding(x):
return np.array(list(map(Match_Smallest, x)))
# what I want to get :
vector_position_outout = A_Finding(vector)
# but Match_Smallest(x) is really too slow
It takes about more than a minute for me to get the output vector A_Finding(vector).我大约需要一分钟多的时间才能得到 output 向量 A_Finding(vector)。 It would like to see if there is any quicker way to do it because Excel was beating me on my way in speed.它想看看是否有更快的方法来做到这一点,因为 Excel 在我的速度上击败了我。
perfplot.show(
setup=lambda n: np.random.rand(n), # or setup=np.random.rand
kernels=[
A_Finding
],
labels=["c_"],
n_range=[10 ** k for k in range(5)],
xlabel="len(a)",
)
Use broadcasting:使用广播:
out = np.sum(np.array((vector_to_match < vector[:, None]) * 1), axis=1) - 1
Or like mentioned @donkopotamus in comments - use searchsorted
:或者像评论中提到的@donkopotamus - 使用searchsorted
:
out = vector_to_match.searchsorted(vector) - 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.