Search code examples
pythonnumpyminminimumclosest

Closest element to a value (Elementwise, numpy array)


I used to use min([a, b], key=lambda x:abs(x-x0)) to find which of a and b are the closest to x0.

a = 1
b = 2
x0 = 1.49
print(min([a, b], key=lambda x:abs(x-x0)))
# >>> 1

Now, a and b are numpy arrays with an arbitrary number of dimensions. I would like to build an array composed of the closest values to x0 between both arrays, element by element.

import numpy as np

a = np.array([[1, 2], [3, 5]])
b = np.array([[6, 2], [6, 2]])

## case 1
x0 = 4
# >>> should return np.array([[6, 2], [3, 5]])

## case 2
x0 = np.array([[1, 2], [3, 4]])
# >>> should return np.array([[1, 2], [3, 5]])

To find the elementwise minimum between two arrays, we can use numpy.minimum. Unfortunately, it does not take lambda functions as arguments.

How should I do ?


Solution

  • Is this what you are looking for?

    np.where(np.abs(a - x0) < np.abs(b - x0), a, b)