在 NumPy 中計算元素級的絕對值
要計算絕對值,我們可以使用兩種方法,**fabs()** 和 **absolute()**。要逐元素返回絕對值,請在 Python NumPy 中使用 numpy.fabs() 方法。這將以浮點數顯示輸出。
要逐元素返回絕對值,您也可以在 Python NumPy 中使用 numpy.absolute() 方法。out 是結果儲存到的位置。如果提供,它必須具有輸入廣播到的形狀。如果未提供或為 None,則返回一個新分配的陣列。元組(僅可能作為關鍵字引數)的長度必須等於輸出的數量。
條件在輸入上廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他地方,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立了一個未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。
步驟
首先,匯入所需的庫 -
import numpy as np
建立一個數組 -
arr = np.array([76, -81, 91, -100, -120, 150, 200])
顯示陣列 -
print("Array...
", arr)獲取陣列的型別 -
print("
Our Array type...
", arr.dtype)
獲取陣列的維度 -
print("
Our Array Dimension...
",arr.ndim)獲取陣列的形狀 -
print("
Our Array Shape...
",arr.shape)
要逐元素返回絕對值,請在 Python NumPy 中使用 numpy.fabs() 方法。這將以浮點數顯示輸出 -
print("
Result...
",np.fabs(arr))要逐元素返回絕對值,請在 Python NumPy 中使用 numpy.absolute() 方法 -
print("
Result...
",np.absolute(arr))
示例
import numpy as np
# Create an array
arr = np.array([76, -81, 91, -100, -120, 150, 200])
# 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 return the absolute value element-wise, use the numpy.fabs() method in Python Numpy
# This displays the output in float
print("
Result...
",np.fabs(arr))
# To return the absolute value element-wise, use the numpy.absolute() method in Python Numpy
print("
Result...
",np.absolute(arr))輸出
Array... [ 76 -81 91 -100 -120 150 200] Our Array type... int64 Our Array Dimension... 1 Our Array Shape... (7,) Result... [ 76. 81. 91. 100. 120. 150. 200.] Result... [ 76 81 91 100 120 150 200]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP