在 Python 中返回陣列沿軸的最大值或忽略任何 NaN 的最大值


要在 Python 中返回陣列的最大值或忽略任何 NaN 的最大值,請使用 numpy.nanmax() 方法。該方法返回一個與 a 形狀相同的陣列,其中指定軸已移除。如果 a 是一個 0 維陣列,或者 axis 為 None,則返回一個 ndarray 標量。返回的資料型別與 a 相同。

第一個引數 a 是一個包含需要求最大值的數字的陣列。如果 a 不是陣列,則嘗試進行轉換。第二個引數 axis 是計算最大值的軸或軸集。預設情況下,計算扁平化陣列的最大值。第三個引數 out 是一個備用輸出陣列,用於放置結果。預設值為 None;如果提供,它必須與預期輸出具有相同的形狀,但如有必要,型別將被轉換。

第四個引數 keepdims 如果將其設定為 True,則減少的軸將作為大小為一的維度保留在結果中。使用此選項,結果將與原始 a 正確廣播。如果該值不是預設值,則 keepdims 將傳遞到 ndarray 子類的 max 方法。如果子類方法沒有實現 keepdims,則將引發任何異常。第五個引數是輸出元素的最小值。必須存在才能允許對空切片進行計算

步驟

首先,匯入所需的庫:

import numpy as np

使用 array() 方法建立一個 numpy 陣列。我們添加了 int 型別和 nan 元素:

arr = np.array([[10, 20, 30], [40, np.nan, 60]])

顯示陣列:

print("Our Array...
",arr)

檢查維度:

print("
Dimensions of our Array...
",arr.ndim)

獲取資料型別:

print("
Datatype of our Array object...
",arr.dtype)

要在 Python 中返回陣列的最大值或忽略任何 NaN 的最大值,請使用 numpy.nanmax()。該方法返回一個與 a 形狀相同的陣列,其中指定軸已移除。如果 a 是一個 0 維陣列,或者 axis 為 None,則返回一個 ndarray 標量。返回的資料型別與 a 相同:

print("
Result (nanmax)...
",np.nanmax(arr, axis = 1))

示例

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type with nan
arr = np.array([[10, 20, 30], [40, np.nan, 60]])

# Display the array
print("Our Array...
",arr) # Check the Dimensions print("
Dimensions of our Array...
",arr.ndim) # Get the Datatype print("
Datatype of our Array object...
",arr.dtype) # To return the maximum of an array or maximum ignoring any NaNs, use the numpy.nanmax() method in Python print("
Result (nanmax)...
",np.nanmax(arr, axis = 1))

輸出

Our Array...
[[10. 20. 30.]
[40. nan 60.]]

Dimensions of our Array...
2

Datatype of our Array object...
float64

Result (nanmax)...
[30. 60.]

更新於:2022年3月1日

115 次檢視

啟動您的職業生涯

完成課程獲得認證

開始
廣告