将NumPy数组的值的符号更改为标量的逐元素符号
要将数组值的符号更改为标量的逐元素符号,请在Python NumPy中使用**numpy.copysign()**方法。copysign()的第一个参数是要更改其符号的值(数组元素)。第二个参数是要复制到第一个参数值的符号。
out是将结果存储到的位置。如果提供,则其形状必须与输入广播到的形状相同。如果没有提供或为None,则返回一个新分配的数组。元组(只能作为关键字参数)的长度必须等于输出的数量。
条件在输入上进行广播。在条件为True的位置,out数组将设置为ufunc结果。在其他位置,out数组将保留其原始值。请注意,如果通过默认的out=None创建未初始化的out数组,则其中条件为False的位置将保持未初始化状态。
步骤
首先,导入所需的库:
import numpy as np
创建一个数组:
arr = np.array([10, 87, -45, -7.9, 6.5, 89])
显示数组:
print("Array...
", arr)获取数组的类型:
print("
Our Array type...
", arr.dtype)
获取数组的维度:
print("
Our Array Dimensions...
",arr.ndim)获取数组中元素的数量:
print("
Number of elements...
", arr.size)
要将数组值的符号更改为标量的逐元素符号,请在Python NumPy中使用numpy.copysign()方法。copysign()的第一个参数是要更改其符号的值(数组元素)。第二个参数是要复制到第一个参数值的符号:
print("
Result...
",np.copysign(arr, -1))示例
import numpy as np
# Create an array
arr = np.array([10, 87, -45, -7.9, 6.5, 89])
# 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)
# To change the sign of array values to that of a scalar, elementwise, use the numpy.copysign() method in Python Numpy
# The 1st parameter of the copysign() is the value (array elements) to change the sign of.
# The 2nd parameter is the sign to be copied to 1st parameter value.
print("
Result...
",np.copysign(arr, -1))输出
Array... [ 10. 87. -45. -7.9 6.5 89. ] Our Array type... float64 Our Array Dimensions... 1 Number of elements... 6 Result... [-10. -87. -45. -7.9 -6.5 -89. ]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP