SciPy - find() 方法



SciPy 的 find() 方法用於查詢滿足給定條件的陣列元素索引。也可以說,此方法返回包含給定字串的 **物理常數** 鍵列表。

在 **NumPy** 中,find() 方法與 **nonzero()** 和 **where()** 類似。以下是這些方法的描述:

  • **nonzero()**: 返回陣列中非零元素的索引。
  • **where()**: 此方法根據輸入陣列元素的索引滿足給定條件。

語法

以下是 SciPy **find()** 方法的語法:

find(key)

引數

此函式只接受一個引數:

  • **key**: key 是一個充當字串的物理常數。

返回值

它有兩種情況:

  • 根據特定模組返回結果。
  • 返回物理常數的結果。

示例 1

以下示例說明了 SciPy **find()** 方法的用法。

from scipy.constants import find, physical_constants
result = find('boltzmann')
print(result)

輸出

以上程式碼產生以下結果:

['Boltzmann constant', 'Boltzmann constant in Hz/K', 'Boltzmann constant in eV/K', 'Boltzmann constant in inverse meter per kelvin', 'Stefan-Boltzmann constant']

示例 2

這裡,我們使用另一個物理常數作為字串引數來顯示結果。

from scipy.constants import find, physical_constants
result = find('radius')
print(result)

輸出

以上程式碼產生以下結果:

['Bohr radius', 'classical electron radius', 'deuteron rms charge radius', 'proton rms charge radius']

示例 3

這裡,我們建立一個稀疏矩陣來填充行和列的資料,並使用 find() 獲取非零元素的行索引、列索引和值。

稀疏矩陣是一種包含大部分為 0 值的矩陣。因此,這種矩陣通常用於機器學習領域,它可以節省計算時間和儲存空間。
import numpy as np
from scipy.sparse import csr_matrix, find

# Create a sparse matrix
A = csr_matrix([[0, 0, 1], [1, 0, 0], [0, 2, 0]])

row, col, data = find(A)

print("The row indices of non-zero elements:", row)
print("The column indices of non-zero elements:", col)
print("The values of non-zero elements:", data)

輸出

以上程式碼產生以下結果:

The row indices of non-zero elements: [0 1 2]
The column indices of non-zero elements: [2 0 1]
The values of non-zero elements: [1 1 2
scipy_reference.htm
廣告
© . All rights reserved.