在 NumPy 数组中查找元素的第一个索引

Manav Narula 2023年1月30日 NumPy NumPy Index
  1. 使用 where() 函数在 NumPy 数组中查找元素的第一个索引
  2. 使用 nonzero() 函数在 NumPy 数组中查找元素的第一个索引
  3. 使用 argmax() 函数在 numpy 数组中查找元素的第一个索引
  4. 使用 index() 函数在 NumPy 数组中查找元素的第一个索引
在 NumPy 数组中查找元素的第一个索引

在本教程中,我们将讨论如何在 numpy 数组中查找元素的第一个索引。

使用 where() 函数在 NumPy 数组中查找元素的第一个索引

numpy 模块中的 where() 函数用于返回一个数组,该数组包含满足某些条件的元素的索引。条件在函数中指定。

我们可以使用它来查找数组中特定值的第一个索引,如下所示。

a = np.array([7, 8, 9, 5, 2, 1, 5, 6, 1])

print(np.where(a == 1)[0][0])

输出:

5

使用 nonzero() 函数在 NumPy 数组中查找元素的第一个索引

nonzero() 函数返回 numpy 数组中所有非零元素的索引。它为多维数组返回多个数组的元组。

where() 函数类似,我们也可以指定条件,以便它也可以返回特定元素的位置。

例如,

a = np.array([7, 8, 9, 5, 2, 1, 5, 6, 1])

print(np.nonzero(a == 1)[0][0])

输出:

5

为了最基本的目的,where()nonzero() 函数看起来很相似。where() 函数的区别在于,当你希望从数组 a 中选取某些条件为 True 时的元素,以及从数组 b 中选取该条件为 False 时的元素。

使用 argmax() 函数在 numpy 数组中查找元素的第一个索引

argmax() 查找数组中最大元素的索引。我们可以在函数中指定相等条件,并找到所需元素的索引。

例如,

a = np.array([7, 8, 9, 5, 2, 1, 5, 6, 1])

print(np.argmax(a == 1))

输出:

5

使用 index() 函数在 NumPy 数组中查找元素的第一个索引

在这种方法中,我们将首先使用 tolist() 函数将数组转换为列表。然后,我们将使用 index() 函数,该函数将返回指定元素的位置。

以下代码实现了这一点。

a = np.array([7, 8, 9, 5, 2, 1, 5, 6, 1])

print(a.tolist().index(1))

输出:

5
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn