0

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)
TornadoEric
  • 399
  • 3
  • 16
  • 1
    Maybe it help np.searchsorted(a.reshape(-1), b.reshape(-1)). Then you can find index from a, because you know shapes. – dragondip Jun 06 '23 at 16:22
  • how do you define 'closest'? With a 1d sorted numeric array, the relevant 'gap' is clear. Not so with a multidim array. – hpaulj Jun 06 '23 at 19:49

0 Answers0