Given two arrays of different size aa
and bb
, I need to replace the elements in aa
with those elements in bb
that are closest.
This is what I have right now. It works [*], but I'm wondering if there's a better way.
import numpy as np
# Some random data
aa = np.random.uniform(0., 1., 100)
bb = np.array([.1, .2, .4, .55, .97])
# For each element in aa, find the index of the nearest element in bb
idx = np.searchsorted(bb, aa)
# For indexes to the right of the rightmost bb element, associate to the last
# bb element.
msk = idx > len(bb) - 1
idx[msk] = len(bb) - 1
# Replace values in aa
aa = np.array([bb[_] for _ in idx])
[*]: actually it almost works. As pointed out in the comments, np.searchsorted doesn't return the index of the closest element, but "indices into a sorted array a such that, if the corresponding elements in v were inserted before the indices, the order of a would be preserved", which is not the same.
You have to calculate the difference between each element in aa
and bb
, and take the minimum:
aa_nearest = bb[abs(aa[None, :] - bb[:, None]).argmin(axis=0)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With