在 NumPy 中計算每個元素的絕對值並將結果儲存到新的位置


要計算每個元素的絕對值,請使用 Python NumPy 中的 **numpy.fabs()** 方法。我們將結果儲存到一個新的陣列中。

此函式返回 x 中資料的絕對值(正值)。不處理複數,請使用 absolute 函式查詢複數資料的絕對值。條件在輸入上進行廣播。在條件為 True 的位置,out 陣列將設定為 ufunc 結果。在其他位置,out 陣列將保留其原始值。請注意,如果透過預設的 out=None 建立未初始化的 out 陣列,則其中條件為 False 的位置將保持未初始化狀態。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個包含一些 NaT 和日期值的陣列:

arr = np.array([-1, 1, 10, 45, 67, 89, -97])

顯示陣列:

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.3, -3.4, 7.6, 5.1, 5.9, 6.8, 9.8])

要計算每個元素的絕對值,請使用 Python NumPy 中的 numpy.fabs() 方法。我們將結果儲存到 arrRes 中:

print("
Compute the absolute values element-wise...
",np.fabs(arr, arrRes))

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

print("
Result...
",arrRes)

示例

import numpy as np

# Create an array with some NaT and date values
arr = np.array([-1, 1, 10, 45, 67, 89, -97])

# 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.3, -3.4, 7.6, 5.1, 5.9, 6.8, 9.8]) # To compute the absolute values element-wise, use the numpy.fabs() method in Python Numpy # The new location where we will store the result is arrRes print("
Compute the absolute values element-wise...
",np.fabs(arr, arrRes)) # Check the value of the new array where our result is stored print("
Result...
",arrRes)

輸出

Array...
[ -1 1 10 45 67 89 -97]

Our Array type...
int64

Our Array Dimensions...
1

Number of elements...
7

Compute the absolute values element-wise...
[ 1. 1. 10. 45. 67. 89. 97.]

Result...
[ 1. 1. 10. 45. 67. 89. 97.]

更新於:2022年2月8日

79 次檢視

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.