返回 NumPy 中特定陣列元素的截斷值


要返回特定元素的截斷值,請在 Python NumPy 中的 **numpy.trunc()** 方法中使用索引值。

該函式返回 x 中每個元素的截斷值。如果 x 是標量,則這是一個標量。標量 x 的截斷值是比 x 更接近零的整數 i。簡而言之,帶符號數字 x 的小數部分將被丟棄。

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

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

步驟

首先,匯入所需的庫 -

import numpy as np

使用 array() 方法建立一個數組 -

arr = np.array([39.5, 57.4, 100.8, 34.9, 76.5, -59.8])

顯示陣列 -

print("Array...
", arr)

獲取陣列的型別 -

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

獲取陣列的維度 -

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

獲取陣列的元素個數 -

print("
Number of elements...
", arr.size)

返回陣列元素的截斷值,逐元素 -

print("
Result (trunc)...
",np.ceil(arr))

要返回特定元素的截斷值,請在 Python NumPy 中的 numpy.trunc() 方法中使用索引值 -

print("
Result (trunc of a specific element)...
",np.trunc(arr[3]))

示例

import numpy as np

# Create an array using the array() method
arr = np.array([39.5, 57.4, 100.8, 34.9, 76.5, -59.8])

# 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 Dimensions...
", arr.ndim) # Get the number of elements in the Array print("
Number of elements...
", arr.size) # Return the truncated value of the array elements, element-wise print("
Result (trunc)...
",np.ceil(arr)) # To return the truncated value of a specific element, use the index value in the numpy.trunc() method in Python Numpy print("
Result (trunc of a specific element)...
",np.trunc(arr[3]))

輸出

Array...
[ 39.5 57.4 100.8 34.9 76.5 -59.8]

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
6

Result (trunc)...
[ 40. 58. 101. 35. 77. -59.]

Result (trunc of a specific element)...
34.0

更新於: 2022年2月8日

104 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.