dbliss - 5 months ago 18

Python Question

I've written the following function:

`import numpy as np`

def _find_nearest(array, value):

"""Find the index in array whose element is nearest to value.

Parameters

----------

array : np.array

The array.

value : number

The value.

Returns

-------

integer

The index in array whose element is nearest to value.

"""

if array.argmax() == array.size - 1 and value > array.max():

return array.size

return (np.abs(array - value)).argmin()

I'd like to vectorize this function, so that I can pass several values at once. That is, I'd like to have

`value`

`_find_nearest`

`value_array`

Can anyone see a way to do this?

Answer

Inside the parent function, where both the `value`

and the `array`

are visible, you can use a `lambda`

to enable the vectorization. I shall call the parent function `main`

```
def main():
value = np.random.rand(10, 1)
array = np.random.rand(100, 100)
vec_nearest = lambda x: _find_nearest(array, x)
np.vectorize(vec_nearest)(value)
```

This will work on one `array`

, and multiple values of `vector`

. The return will be an array.