測試 NumPy 陣列值是否為無窮大,並將結果儲存到新位置
要測試陣列值是否為無窮大,請在 Python NumPy 中使用 **numpy.isinf()** 方法。我們將儲存結果的新位置是一個新陣列。返回與 x 形狀相同的布林陣列,其中 x == +/-inf 為 True,否則為 False。
NumPy 使用 IEEE 算術二進位制浮點數標準 (IEEE 754)。如果第一個引數是標量時提供了第二個引數,或者第一個和第二個引數具有不同的形狀,則會產生錯誤。
步驟
首先,匯入所需的庫 -
import numpy as np
建立一個包含一些無窮大值的陣列 -
arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])
顯示陣列 -
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, 5, 5, 5, 5, 5, 5])
要測試陣列值是否為無窮大,請在 Python NumPy 中使用 numpy.isinf() 方法。我們將儲存結果的新位置是 arrRes -
print("
Test array for infiniteness...
",np.isinf(arr, arrRes))
檢查儲存結果的新陣列的值 -
print("
Result...
",arrRes)示例
import numpy as np
# Create an array with some inf values
arr = np.array([1, 2, 10, 50, -np.inf, 0., np.inf])
# 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, 5, 5, 5, 5, 5, 5])
# To test array values for infiniteness, use the numpy.isfinite() method in Python Numpy
# The new location where we will store the result is arrRes
print("
Test array for infiniteness...
",np.isinf(arr, arrRes))
# Check the value of the new array where our result is stored
print("
Result...
",arrRes)輸出
Array... [ 1. 2. 10. 50. -inf 0. inf] Our Array type... float64 Our Array Dimensions... 1 Number of elements... 7 Test array for infiniteness... [0 0 0 0 1 0 1] Result... [0 0 0 0 1 0 1]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP