在 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