📜  如何计算 NumPy 数组的元素绝对值?

📅  最后修改于: 2022-05-13 01:54:23.821000             🧑  作者: Mango

如何计算 NumPy 数组的元素绝对值?

让我们看看查找 NumPy 数组的元素绝对值的程序。为了完成这项任务,我们使用 NumPy 库的numpy.absolute()函数。这个数学函数有助于计算数组中每个元素的绝对值。

让我们看一个例子:

示例 1:一维数组的元素绝对值。

Python3
# import library
import numpy as np
  
# create a numpy 1d-array
array = np.array([1, -2, 3])
  
print("Given array:\n", array)
  
# find element-wise
# absolute value
rslt = np.absolute(array)
  
print("Absolute array:\n", rslt)


Python3
# import library
import numpy as np
  
# create a numpy 2d-array
array = np.array([[1, -2, 3],
                  [-4, 5, -6]])
  
print("Given array:\n",
      array)
  
# find element-wise
# absolute value
rslt = np.absolute(array)
  
print("Absolute array:\n",
      rslt)


Python3
# import library
import numpy as np
  
# create a numpy 3d-array
array = np.array([
    [[1, -2, 3],
     [-4, 5, -6]],
                   
    [[-7.5, -8.22, 9.0],
     [10.0, 11.5, -12.5]]
                 ])
  
print("Given array:\n",
      array)
  
# find element-wise
# absolute value 
rslt = np.absolute(array)
  
print("Absolute array:\n",
      rslt)


输出:

Given array:
[ 1 -2  3]
Absolute array:
[1 2 3]

示例 2:二维数组的元素绝对值。

Python3

# import library
import numpy as np
  
# create a numpy 2d-array
array = np.array([[1, -2, 3],
                  [-4, 5, -6]])
  
print("Given array:\n",
      array)
  
# find element-wise
# absolute value
rslt = np.absolute(array)
  
print("Absolute array:\n",
      rslt)

输出:

Given array:
[[ 1 -2  3]
[-4  5 -6]]
Absolute array:
[[1 2 3]
[4 5 6]]

示例 3: 3d 数组的元素绝对值。

Python3

# import library
import numpy as np
  
# create a numpy 3d-array
array = np.array([
    [[1, -2, 3],
     [-4, 5, -6]],
                   
    [[-7.5, -8.22, 9.0],
     [10.0, 11.5, -12.5]]
                 ])
  
print("Given array:\n",
      array)
  
# find element-wise
# absolute value 
rslt = np.absolute(array)
  
print("Absolute array:\n",
      rslt)

输出:

Given array:
[[[  1.    -2.     3.  ]
 [ -4.     5.    -6.  ]]

[[ -7.5   -8.22   9.  ]
 [ 10.    11.5  -12.5 ]]]
Absolute array:
[[[ 1.    2.    3.  ]
 [ 4.    5.    6.  ]]

[[ 7.5   8.22  9.  ]
 [10.   11.5  12.5 ]]]