Consider the following three-dimensional array of size (1000,2000,200)
and corresponding two-dimensional array of size (1000,2000)
. Both arrays do not contain NaNs:
import numpy as np
a = np.random.randint(0,50,size=(1000,2000,200))
b = np.random.randint(0,50,size=(1000,2000,))
I'd like to find the appropriate index at a[i,j] that is closest to the single value at b[i,j]. The first approach was to use np.searchsorted
:
indices = np.searchsorted(a, b)
However, the challenge is that this works only on 1-D dimensional arrays and returns (as anticipated) ValueError: object too deep for desired array
I've inspected this related question, which is tailored to moving across a two-dimensional array. Is there a time-efficient method to return the indices at each point [i,j] instead of writing a non-vectorized function?
Expansion: I've made an alteration to the current approach, which use differential positioning across the entire array. This looks as follows:
b_3d: np.repeat(b[:, :, np.newaxis], a.shape[2], axis=2)
diff = np.abs(a - b_3d)
indices = np.argmin(diff, axis=2)