0

The given value is 6.6. But the value 6.6 is not in the array (data below). But the nearest value to the given value is 6.7. How can I get this position?

import numpy as np
data = np.array([[2.0, 3.0, 6.5, 6.5, 12.0],[1,2,3,4,5]],dtype=float)
6
  • This is also similar: stackoverflow.com/questions/8527952/… Commented Apr 26, 2014 at 8:11
  • @YuvalAdam looking for more direct way of doing it.@merlin2011 Commented Apr 26, 2014 at 8:30
  • Can you assume the array is sorted? Please provide more detail. Commented Apr 26, 2014 at 8:32
  • @EML The index position should be exact to the original array Commented Apr 26, 2014 at 8:34
  • What do you mean by a more "direct" way? Looking at offsets seems to be the best way to do it. Commented Apr 26, 2014 at 8:39

2 Answers 2

3

You can get like this:

data[(np.fabs(data-6.6)).argmin(axis=0)]

output:

6.7
  1. find the absolute diff on each element
  2. Find the minimum from the result and get the element from index

EDIT: for 2d:

If it is python 2.x:

map(lambda x:x[(np.fabs(x-6.6)).argmin(axis=0)], data)

python 3.x:

[r for r in map(lambda x:x[(np.fabs(x-6.6)).argmin(axis=0)], data)]

results in returning nearest value in each row.

One value from all:

data=data.flatten()
print data[(np.fabs(data-6.6)).argmin(axis=0)]

index position from each row:

ip = map(lambda x:(np.fabs(x-6.6)).argmin(axis=0), data)
Sign up to request clarification or add additional context in comments.

13 Comments

The data shape is 2d array
In your original question it was not 2d. Can you tell me you want one nearest value from all or you want minimum value for each row?
one nearest value from all
sorry that i changed into 2d because i did mistake while posting
Please find my edited answer.
|
1

This is the simplest way I think.

>>> data = np.array([[2.0, 3.0, 6.5, 6.5, 12.0],[1,2,3,4,5]], dtype=float)
>>> data2 = np.fabs(data - 6.6)
>>> np.unravel_index(data2.argmin(), data2.shape)
(0, 2)

See np.argmin and np.unravel_index function.

Comments