在 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.]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP