Bilja - 8 months ago 32

Python Question

Elements in arrays *x* and *y* are floats. I would like to find elements in array *x* which have values as close as possible to the ones in array *y* (for each value in array *y* - one element in array *x*). Also array *x* contains >10^6 elements and array *y* around 10^3, and this is part of a *for loop* so it should be done preferably fast.

I tried to avoid making it as a new for loop so I did this, but it is very slow for a big y array

`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]

I'm new to Python, so any suggestion is welcome!

Answer

The following gives the desired result.

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

It `tile`

s `x`

for each element in `y`

(`len(y)`

), transposes (`.T`

) this tiled array, subtracts `y`

, re-transposes it, takes the `abs`

olute value of differences, determines the indexes of the minimum values using `argmin`

(over `axis=1`

), and finally gets the values from these indexes of `x`

.