-2

我想在数组本身的一维 NumPy 数组中找到随机选择的数字的索引/位置,但是当我尝试以下操作时:

a = np.array(np.linspace(1,10,10))
b = np.random.choice(a)
print(a.index(b))

它不起作用,无法弄清楚问题出在哪里。有人有想法吗?

提前致谢!

编辑:如果 NumPy 数组中的值相同,您如何仅索引随机选择的值,例如:

a = np.array(np.linspace(10,10,10))
4

3 回答 3

1

你必须使用where函数作为已经回答这里有一个 NumPy 函数来返回数组中某物的第一个索引吗?

import numpy as np
a = np.array(np.linspace(1,10,10))
b = np.random.choice(a)
print(np.where(a==b))

如果值相同,则where返回多个索引,例如:

a = np.array(np.linspace(10,10,10))
print(np.where(a==10))

>>> (array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),)

这里所有索引都被翻转,因为 10 处于所有位置。

于 2019-11-12T13:02:31.880 回答
0

NumPy 的where()函数可以满足您的需求,如其他答案中所述。如果您只有一维数组并且您只想要aequals的第一个元素的索引bwhere()则既笨重又低效。相反,您可以使用

import numpy as np
a = np.linspace(1, 10, 10)  # Hint: the np.array() is superfluous
b = np.random.choice(a)
index = next(i for i, el in enumerate(a) if el == b)
print(index, a[index])
于 2019-11-12T13:20:51.210 回答
0

这将为您提供所需的输出:

np.where(a==b)[0][0]
于 2019-11-12T13:05:35.507 回答