在 NumPy 中返回陣列元素的上限並將其儲存到新位置


要返回陣列元素的上限(逐元素),請在 Python NumPy 中使用 **numpy.ceil()** 方法。我們將儲存結果的新位置是一個新陣列。

標量 x 的上限是最小的整數 i,使得 i >= x。通常表示為 **$\mathrm{\lceil X \rceil}$**。該函式返回 x 中每個元素的上限,資料型別為浮點數。如果 x 是標量,則這是一個標量。out 是儲存結果的位置。如果提供,它必須具有輸入廣播到的形狀。如果沒有提供或為 None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。

步驟

首先,匯入所需的庫 -

import numpy as np

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

arr = np.array([48.7, 100.8, 50.7, 67.9, 34.5, 69.8])

顯示陣列 -

print("Array...
", arr)

獲取陣列的型別 -

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

獲取陣列的維度 -

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

獲取陣列中元素的數量 -

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

建立另一個具有相同形狀的陣列來儲存結果 -

arrRes = np.array([5.2, 10.1, 15.7, 20.2, 25.9, 45.9])

要返回陣列元素的上限(逐元素),請在 Python NumPy 中使用 numpy.ceil() 方法。我們將儲存結果的新位置是 arrRes -

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

檢查儲存結果的新陣列的值 -

print("
Result...
",arrRes)

示例

import numpy as np

# Create an array using the array() method
arr = np.array([48.7, 100.8, 50.7, 67.9, 34.5, 69.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) # Create another array with the same shape to store the result arrRes = np.array([5.2, 10.1, 15.7, 20.2, 25.9, 45.9]) # To return the ceil of the array elements, element-wise, use the numpy.ceil() method in Python Numpy # The new location where we will store the result is arrRes print("
Result (ceil)...
",np.ceil(arr, arrRes)) # Check the value of the new array where our result is stored print("
Result...
",arrRes)

輸出

Array...
[ 48.7 100.8 50.7 67.9 34.5 69.8]

Our Array type...
float64

Our Array Dimensions...
1

Number of elements...
6

Result (ceil)...
[ 49. 101. 51. 68. 35. 70.]

Result...
[ 49. 101. 51. 68. 35. 70.]

更新於: 2022年2月8日

108 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.