在 Python 中返回输入数组的公共标量类型
要返回输入数组的公共标量类型,请在 Python NumPy 中使用 numpy.common_type() 方法。第一个参数是输入数组。返回类型始终为不精确(即浮点数)标量类型,即使所有数组都是整数数组。如果其中一个输入是整数数组,则返回的最小精度类型为 64 位浮点数数据类型。
除 int64 和 uint64 之外的所有输入数组都可以安全地转换为返回的数据类型,而不会丢失信息。
步骤
首先,导入所需的库 -
import numpy as np
要返回输入数组的公共标量类型,请使用 numpy.common_type() 方法 -
print("Using the common_type() method in Numpy\n")
print("Result...",np.common_type(np.arange(3,dtype=np.float32)))
print("Result...",np.common_type(np.arange(3,dtype=np.float32), np.arange(2)))
print("Result...",np.common_type(np.arange(3), np.array([22, 2.j]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3,dtyp =np.int32), np.arange(2))) Example示例
import numpy as np
# To return a scalar type which is common to the input arrays, use the numpy.common_type() method in Python Numpy.
# The 1st parameter is the input array(s).
print("Using the common_type() method in Numpy\n")
print("Result...",np.common_type(np.arange(3,dtype=np.float32)))
print("Result...",np.common_type(np.arange(3,dtype=np.float32), np.arange(2)))
print("Result...",np.common_type(np.arange(3), np.array([22, 2.j]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3), np.array([22, 39]), np.array([32.9])))
print("Result...",np.common_type(np.arange(3,dtype=np.int32), np.arange(2)))输出
Using the common_type() method in Numpy Result... <class 'numpy.float32'> Result... <class 'numpy.float64'> Result... <class 'numpy.complex128'> Result... <class 'numpy.float64'> Result... <class 'numpy.float64'>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP