As described here, if you want to find the closest value in a list for a number it can done as follows:
array = np.array([1,3,6,7,8])
value = 5
absolute_val_array = np.abs(array - value)
print(absolute_val_array)
smallest_difference_index = absolute_val_array.argmin()
closest_element = array[smallest_difference_index]
print(closest_element)
Which provides the right output:
[4 2 1 2 3]
6
Which would be the most appropiate way to convert at once a numpy array instead of a single value?
array = np.array([1,3,6,7,8])
values = [5,6,7,8,1,9,10]
absolute_val_array = np.abs(array - values)
print(absolute_val_array)
smallest_difference_index = absolute_val_array.argmin()
closest_element = array[smallest_difference_index]
print(closest_element)
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-998d06731928> in <module>
1 array = np.array([1,3,6,7,8])
2 values = [5,6,7,8,1,9,10]
----> 3 absolute_val_array = np.abs(array - values)
4 print(absolute_val_array)
5 smallest_difference_index = absolute_val_array.argmin()
ValueError: operands could not be broadcast together with shapes (5,) (7,)