在 NumPy 陣列中查詢最大和最小元素


著名的開源 Python 庫 NumPy 用於數值計算。它支援大型多維陣列和矩陣,以及大量可用於有效處理這些陣列的複雜數學運算。

在使用 NumPy 陣列時,經常需要查詢最大和最小元素。

方法一:使用 max() 和 min() 函式

以下程式碼演示了建立整數陣列的過程。然後,我們分別使用 max() 和 min() 函式查詢陣列中最大和最小的元素。

演算法

  • 匯入所需的 Numpy 庫。

  • 建立一個包含整數資料的 1D numpy 陣列。

  • 使用 max() 和 min() 函式查詢最大和最小元素。

  • 列印結果。

示例

# Import numpy library
import numpy as np
arry = np.array([69, 96, 99, 14, 3])

# Finding the maximum element
max_elent = np.max(arry)

# Finding the maximum element
min_elent = np.min(arry)

print("max element in the array is:", max_elent)
print("min element in the array is:", min_elent)

輸出

Max element in the array is: 99
Min element in the array is: 3

方法二:在 NumPy 中使用 Argmax() 和 Argmin() 函式

以下程式碼演示瞭如何使用 argmax() 和 argmin() 函式在給定陣列中查詢最小和最大元素。

演算法

  • 匯入 numpy 庫。

  • 建立一個包含整數資料的 numpy 陣列。

  • 獲取最大和最小元素的索引。

  • 獲取最大和最小元素及其索引。

  • 列印資訊。

示例

import numpy as npy
ary = npy.array([2023, 56, 400, 2025, 3])

# fetching index of the maximum and minimum element
max_idx = npy.argmax(ary)
min_idx = npy.argmin(ary)

# Get the maximum and minimum element
max_elnt = ary[max_idx]
min_elnt = ary[min_idx]

print("Max_element in the array is:", max_elnt)
print("Min_element in the array is:", min_elnt)

輸出

Max_element in the array is: 2025
Min_element in the array is: 3

方法三:使用 sort() 方法

在本例中,我們將建立一個包含一些整數的 numpy 陣列。使用 sort() 方法對陣列的元素進行排序,然後我們可以從排序後的陣列的首尾索引獲取最小和最大元素。

演算法

  • 匯入 numpy 庫。

  • 建立一個包含隨機元素的 numpy 陣列。

  • 使用 sort() 方法對陣列進行排序。

  • 透過訪問第一個元素可以得到陣列中最小的元素。

  • 透過訪問最後一個元素可以得到陣列中最大的元素。

  • 列印資訊。

示例

import numpy as npy
ary = npy.array([420, 99, 840, 366, 9])
ary.sort()

# Get the minimum and maximum element after sorting
min_elnt = ary[0]
max_elnt = ary[-1]

print("max_ele in the array is:", min_elnt)
print("min_ele in the array is:", max_elnt)

輸出

max_ele in the array is: 9
min_ele in the array is: 840

方法四:使用 Amax() 和 Amin() 函式

在這個例子中,我們將建立一個二維 NumPy 陣列,並使用 amax() 和 amin() 函式查詢陣列的最大和最小元素。

演算法

  • 匯入 numpy 庫。

  • 初始化一個二維 numpy 陣列。

  • 使用 amax() 和 amin() 函式分別確定陣列中的最大和最小元素。

  • 顯示所需的資訊。

import numpy as nmp
ary = nmp.array([[17, 23, 53], [466, 5, 76]])

# Finding max and min element
max_elnt = nmp.amax(ary)
min_elnt = nmp.amin(ary)

print("max element in the array is:", max_elnt)
print("min element in the array is:", min_elnt)

輸出

max element in the array is: 466
min element in the array is: 5

結論

max() 和 min() 函式對於處理大型資料高效且直接,但它們不提供元素索引。

amax() 和 amin() 函式適用於一維和多維陣列。但是,與其他方法相比,它速度較慢,需要更多記憶體來儲存陣列。

更新於:2023年8月23日

1K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.