在 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