返回 NumPy 中数字的符号的逐元素指示
要返回数字的符号的逐元素指示,请在 Python NumPy 中使用 **numpy.sign()** 方法。
如果 x < 0,则符号函数返回 -1;如果 x==0,则返回 0;如果 x > 0,则返回 1。对于 nan 输入,返回 nan。对于复数输入,如果 x.real != 0,则符号函数返回 sign(x.real) + 0j;否则返回 sign(x.imag) + 0j。
对于复数 nan 输入,返回 complex(nan, 0)。在复数的常用符号定义中,不止一个。此处使用的定义等效于 x/x*x,这与常见的替代方案 x/|x| 不同。
步骤
首先,导入所需的库 -
import numpy as np
使用 array() 方法创建具有浮点类型的数组 -
arr = np.array([50.8, 120.3, 200.7, -320.1, -450.4, 0])
显示数组 -
print("Array...
", arr)获取数组的类型 -
print("
Our Array type...
", arr.dtype)
获取数组的维度 -
print("
Our Array Dimension...
",arr.ndim)获取数组的形状 -
print("
Our Array Shape...
",arr.shape)
要返回数字的符号的逐元素指示,请使用 numpy.sign() 方法 -
print("
Result...
",np.sign(arr))示例
import numpy as np
# Create an array with float type using the array() method
arr = np.array([50.8, 120.3, 200.7, -320.1, -450.4, 0])
# 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 an element-wise indication of the sign of a number, use the numpy.sign() method in Python Numpy
print("
Result...
",np.sign(arr))输出
Array... [ 50.8 120.3 200.7 -320.1 -450.4 0. ] Our Array type... float64 Our Array Dimension... 1 Our Array Shape... (6,) Result... [ 1. 1. 1. -1. -1. 0.]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP