在 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'>

更新于: 2022-02-24

369 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.