在 numpy 数组中搜索元素的索引

Searching an element's index in a numpy array

我有一个 "distances" numpy 数组。我想找到一个元素的索引。我使用了 numpy.where 条件,但它没有返回索引。相反,它只是返回带有空数组的元素类型,如下所示:

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

如何获取元素的索引?请帮忙。谢谢

这是我的代码:

distances = distances_query_training(features_train, features_test[2])

print min(distances)

print type(distances)

pos = np.where(distances == 0.03471681)

print pos

下面是输出:

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

不要使用等于浮点值,使用 isclose():

import numpy as np

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

np.where(np.isclose(a, 0.3, atol=1e-4))

您需要所有相近的元素还是只需要最匹配的一个? 我通常会做这样的事情来获取值的最接近索引

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