在NumPy中將陣列元素舍入到最接近的整數


要將陣列元素舍入到最接近的整數,請在Python NumPy中使用**numpy.rint()**方法。對於正好位於舍入後的十進位制值之間的值,NumPy會舍入到最接近的偶數值。

out 是儲存結果的位置。如果提供,則其形狀必須與輸入廣播到的形狀相同。如果不提供或為 None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

條件在輸入上進行廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他地方,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。

步驟

首先,匯入所需的庫:

import numpy as np

使用 array() 方法建立一個浮點型陣列:

arr = np.array([50.8, 120.3, 200.7, 320.1, 450.4, 500.6])

顯示陣列:

print("Array...
", arr)

獲取陣列的型別:

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

獲取陣列的維度:

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

獲取陣列的形狀:

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

要將陣列元素舍入到最接近的整數,請在Python NumPy中使用numpy.rint()方法。對於正好位於舍入後的十進位制值之間的值,NumPy會舍入到最接近的偶數值:

print("
Result (rounded)...
",np.rint(arr))

示例

import numpy as np

# Create an array with float type using the array() method
arr = np.array([50.8, 120.3, 200.7, 320.1, 450.4, 500.6])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To round elements of the array to the nearest integer, use the numpy.rint() method in Python Numpy # For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. print("
Result (rounded)...
",np.rint(arr))

輸出

Array...
[ 50.8 120.3 200.7 320.1 450.4 500.6]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result (rounded)...
[ 51. 120. 201. 320. 450. 501.]

更新於:2022年2月8日

8K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告