数组 x 和 y 中的元素是 float 。我想找到数组 x 中的元素,其值尽可能接近数组 y 中的元素(对于数组 y 中的每个值- 数组 x 中的一个元素)。此外,x 数组包含 >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 的新手,所以欢迎任何建议!
请您参考如下方法:
它以 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)
