我试图找到一些文档来了解 dtypes 是如何组合的。例如:
x : np.int32 = ...
y : np.float64 = ...
- 将是什么类型的
x + y
? - 它取决于运营商(这里
+
)吗? - 它是否取决于它的存储位置(
z = x + y
vsz[...] = x + y
)?
我正在寻找描述这种情况的文档的一部分,但到目前为止我是两手空空的。
我试图找到一些文档来了解 dtypes 是如何组合的。例如:
x : np.int32 = ...
y : np.float64 = ...
x + y
?+
)吗?z = x + y
vs z[...] = x + y
)?我正在寻找描述这种情况的文档的一部分,但到目前为止我是两手空空的。
如果数据类型不匹配,那么 NumPy 会尽可能将数据向上转换为精度更高的数据类型。并且它不依赖于我们所做的(算术)操作的类型或我们分配给的变量,除非该变量已经具有其他一些 dtype。这是一个小插图:
In [14]: x = np.arange(3, dtype=np.int32)
In [15]: y = np.arange(3, dtype=np.float64)
# `+` is equivalent to `numpy.add()`
In [16]: summed = x + y
In [17]: summed.dtype
Out[17]: dtype('float64')
In [18]: np.add(x, y).dtype
Out[18]: dtype('float64')
如果您没有明确分配数据类型,则结果将向上转换为给定输入的较高数据类型。例如,numpy.add()
接受一个dtype
kwarg,您可以在其中指定结果数组的数据类型。
并且,可以通过使用检查是否可以根据转换规则安全地转换两种不同的数据类型numpy.can_cast()
为了完整起见,我添加了以下numpy.can_cast()
矩阵:
>>> def print_casting_matrix(ntypes):
... ntypes_ex = ["X"] + ntypes.split()
... print("".join(ntypes_ex))
... for row in ntypes:
... print(row, sep='\t', end=''),
... for col in ntypes:
... print(int(np.can_cast(row, col)), sep='\t', end='')
... print()
>>> print_casting_matrix(np.typecodes['All'])
并且输出将是以下矩阵,它显示了哪些 dtypes 可以安全地转换(用 表示1
)和哪些 dtypes 不能转换(用 表示0
),按照从转换(沿轴 0)到转换(轴 1 )的顺序) :
# to casting -----> ----->
X?bhilqpBHILQPefdgFDGSUVOMm
?11111111111111111111111101
b01111110000001111111111101
h00111110000000111111111101
i00011110000000011011111101
l00001110000000011011111101
q00001110000000011011111101
p00001110000000011011111101
B00111111111111111111111101
H00011110111110111111111101
I00001110011110011011111101
L00000000001110011011111101
Q00000000001110011011111101
P00000000001110011011111101
e00000000000001111111111100
f00000000000000111111111100
d00000000000000011011111100
g00000000000000001001111100
F00000000000000000111111100
D00000000000000000011111100
G00000000000000000001111100
S00000000000000000000111100
U00000000000000000000011100
V00000000000000000000001100
O00000000000000000000001100
M00000000000000000000001110
m00000000000000000000001101
由于字符很神秘,我们可以使用以下内容更好地理解上述转换矩阵:
In [74]: for char in np.typecodes['All']:
...: print(char, " --> ", np.typeDict[char])
输出将是:
? --> <class 'numpy.bool_'>
b --> <class 'numpy.int8'>
h --> <class 'numpy.int16'>
i --> <class 'numpy.int32'>
l --> <class 'numpy.int64'>
q --> <class 'numpy.int64'>
p --> <class 'numpy.int64'>
B --> <class 'numpy.uint8'>
H --> <class 'numpy.uint16'>
I --> <class 'numpy.uint32'>
L --> <class 'numpy.uint64'>
Q --> <class 'numpy.uint64'>
P --> <class 'numpy.uint64'>
e --> <class 'numpy.float16'>
f --> <class 'numpy.float32'>
d --> <class 'numpy.float64'>
g --> <class 'numpy.float128'>
F --> <class 'numpy.complex64'>
D --> <class 'numpy.complex128'>
G --> <class 'numpy.complex256'>
S --> <class 'numpy.bytes_'>
U --> <class 'numpy.str_'>
V --> <class 'numpy.void'>
O --> <class 'numpy.object_'>
M --> <class 'numpy.datetime64'>
m --> <class 'numpy.timedelta64'>