按照 Python 中的标准强制转换规则确定常见类型
要按照标准强制转换规则确定常见类型,请在 Python NumPy 中使用numpy.find_common_type()方法。第一个参数是表示数组的 dtypes 或可转换对象 dtypes 的列表。第二个参数是表示标量的 dtypes 或可转换对象 dtypes 的列表。
find_common_type()方法返回通用数据类型,忽略scalar_types而使用array_types中的最大值,除非scalar_types的最大值的类型不同(dtype.kind)。如果不理解类型,则返回None。
步骤
首先,导入必要的库 −
import numpy as np
在 NumPy 中使用 find_common_type()方法。按照标准强制转换规则确定常见类型 −
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([np.float32], [complex]))
print("Result...",np.find_common_type([np.float64], [complex]))
print("Result...",np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...",np.find_common_type([np.int64], [complex]))
print("Result...",np.find_common_type([np.int64], [np.float64]))示例
import numpy as np
# To determine common type following standard coercion rules, use the numpy.find_common_type() method in Python numpy
# The 1st argument is a list of dtypes or dtype convertible objects representing arrays.
# The 2nd argument is A list of dtypes or dtype convertible objects representing scalars.
print("Using the find_common_type() method in Numpy\n")
# Determine common type following standard coercion rules
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([], [np.int64, np.float32, complex]))
print("Result...",np.find_common_type([np.float32], [np.int64, np.float64]))
print("Result...",np.find_common_type([np.float32], [complex]))
print("Result...",np.find_common_type([np.float64], [complex]))
print("Result...",np.find_common_type(['f4', 'i4'], ['c8']))
print("Result...",np.find_common_type([np.int64], [complex]))
print("Result...",np.find_common_type([np.int64], [np.float64]))输出
Using the find_common_type() method in Numpy Result... float32 Result... complex128 Result... float32 Result... complex128 Result... complex128 Result... complex128 Result... complex128 Result... float64
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP