创建NumPy dtype对象的规范方法



NumPy提供了许多不同的方法来创建dtype对象:

import numpy

# Full name
print(numpy.dtype("uint16"))
# >>> dtype('uint16')
# Short name
print(numpy.dtype("u2"))
# >>> dtype('uint16')
# Scalar type
print(numpy.dtype(numpy.uint16))
# >>> dtype('uint16')
# Format char from the "struct" module
print(numpy.dtype("H"))
# >>> dtype('uint16')

什么是的规范和推荐方式

查看的文档

In [45]: np.uint16?
Init signature: np.uint16(self, /, *args, **kwargs)
Docstring:     
Unsigned integer type, compatible with C ``unsigned short``.
Character code: ``'H'``.
Canonical name: ``np.ushort``.
Alias *on this platform*: ``np.uint16``: 16-bit unsigned integer (0 to 65535).
File:           /usr/local/lib/python3.6/dist-packages/numpy/__init__.py
Type:           type

np.uint16实际上是一个可以创建numpy数组或标量的函数

In [50]: np.uint16([1,2,3])
Out[50]: array([1, 2, 3], dtype=uint16)
In [51]: type(np.uint16(12))
Out[51]: numpy.uint16
In [52]: np.uint16(12)
Out[52]: 12

np.dtype被设置为解析/理解各种字符串。注意文档中的character codecanonical name。CCD_ 5也是一个函数。

In [56]: np.ushort([1,2,3])
Out[56]: array([1, 2, 3], dtype=uint16)

我不确定是否存在";规范的";或字符串备选方案中的优选形式。

Out[56]: array([1, 2, 3], dtype=uint16)
In [57]: np.array([1,2,3], 'u2')
Out[57]: array([1, 2, 3], dtype=uint16)
In [58]: np.array([1,2,3], 'H')
Out[58]: array([1, 2, 3], dtype=uint16)
In [59]: np.array([1,2,3], 'ushort')
Out[59]: array([1, 2, 3], dtype=uint16)

https://numpy.org/doc/stable/reference/arrays.dtypes.html

In [64]: np.typecodes
Out[64]: 
{'Character': 'c',
'Integer': 'bhilqp',
'UnsignedInteger': 'BHILQP',
'Float': 'efdg',
'Complex': 'FDG',
'AllInteger': 'bBhHiIlLqQpP',
'AllFloat': 'efdgFDG',
'Datetime': 'Mm',
'All': '?bhilqpBHILQPefdgFDGSUVOMm'}
In [65]: np.typeDict
Out[65]: 
{'?': numpy.bool_,
0: numpy.bool_,
'byte': numpy.int8,
'b': numpy.int8,
1: numpy.int8,
'ubyte': numpy.uint8,
'B': numpy.uint8,
...

注意,多字节字符码也可以具有字节顺序指示符,例如<H>H。我们通常不使用这些,但有时在处理其他语言的二进制文件时,我们需要它们。

最新更新