Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace elements in numpy array with closest value in another array

Tags:

python

numpy

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.

like image 268
Gabriel Avatar asked Oct 19 '25 06:10

Gabriel


1 Answers

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)]
like image 200
Daniel Avatar answered Oct 20 '25 20:10

Daniel