Python:如何在数组x中查找值接近数组y中元素的元素?

2024-09-28 22:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

数组xy中的元素是浮点数。我想在arrayx中找到尽可能接近arrayy中的元素(对于arrayy中的每个值-arrayx中的一个元素)。同样,arrayx包含大约10^6个元素,数组y大约为10^3,这是for循环的一部分,因此最好快速完成。在

我试图避免把它作为一个新的for循环,所以我这样做了,但是对于一个大的y数组来说,这是非常慢的

x = np.array([0, 0.2, 1, 2.4, 3,  5]); y = np.array([0, 1, 2]);
diff_xy = x.reshape(1,len(x)) - y.reshape(len(y),1);
diff_xy_abs = np.fabs(diff_xy);
args_x = np.argmin(diff_xy_abs, axis = 1);
x_new = x[args_x]

我是Python新手,所以欢迎任何建议!在


Tags: 元素forlennpargsdiffabs数组
3条回答

它是以x和y的顺序为代价的,但是这些代码是否满足您的性能需求?Rem:x中的相同值可以用于y的多个值

import numpy as np

# x = np.array([0, 0.2, 1, 2.4, 3,  5]);
# y = np.array([0, 1, 2]);
x = np.random.rand(10**6)*5000000
y = (np.random.rand(10**3)*5000000).astype(int)

x_new = np.zeros(len(y))  # Create an 'empty' array for the result

x.sort()  # could be skipped if already sorted
y.sort()  # could be skipped if already sorted

len_x = len(x)
idx_x = 0
cur_x = x[0]

for idx_y, cur_y in enumerate(y):
    while True:
        if idx_x == len_x-1: 
            # If we are at the end of x, the last value is the best value
            x_new[idx_y] = cur_x
            break
        next_x = x[idx_x+1]
        if abs(cur_y - cur_x) < abs(cur_y - next_x):
            # If the current value of x is better than the next, keep it
            x_new[idx_y] = cur_x
            break
        # Check for the next value
        idx_x += 1
        cur_x = next_x

print(x_new)

下面给出了期望的结果。在

x[abs((np.tile(x, (len(y), 1)).T - y).T).argmin(axis=1)]

最后,使用^{cd2}

也许对较大的数组进行排序,然后从中对较小数组的值进行二进制搜索,如果找到的是最接近的值,并且在附近的索引中相邻的值;如果找不到,则最接近的值将紧靠故障点。在

相关问题 更多 >