2

I have a "distances" numpy array. I want to find the index of an element. I used numpy.where condition but it is not returning the index. Instead, it is just returning the type of the element with an empty array, like so:

(array([], dtype=int64),)

What should I do to get the index of the element? Please help. Thanks.

This is my code:

distances = distances_query_training(features_train, features_test[2])

print min(distances)

print type(distances)

pos = np.where(distances == 0.03471681)

print pos

And the following is the output:

0.0347168063061
(array([], dtype=int64),)

2 Answers 2

2

Don't use equal to float values, use isclose():

import numpy as np

np.random.seed(1)
a = np.random.rand(1000)

np.where(np.isclose(a, 0.3, atol=1e-4))
Sign up to request clarification or add additional context in comments.

Comments

1

Do you need all the close elements or just the best matching one? I usually do something like this to get the closest index for a value

def nearest_arg(array, value):
    idx = (np.abs(array - value)).argmin()
    return idx

1 Comment

I needed the best matching one. And your function works really well. Thanks for the help. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.