Python 创建NumPy dtype对象的规范方法

Python 创建NumPy dtype对象的规范方法,python,numpy,Python,Numpy,NumPy提供了许多不同的方法来创建数据类型对象: 导入numpy #全名 打印(numpy.dtype(“uint16”)) #>>>数据类型('uint16') #简称 打印(numpy.dtype(“u2”)) #>>>数据类型('uint16') #标量类型 打印(numpy.dtype(numpy.uint16)) #>>>数据类型('uint16') #格式化“struct”模块中的字符 打印(numpy.dtype(“H”)) #>>>数据类型('uint16') 规范的推荐方法

NumPy提供了许多不同的方法来创建数据类型对象:

导入numpy
#全名
打印(numpy.dtype(“uint16”))
#>>>数据类型('uint16')
#简称
打印(numpy.dtype(“u2”))
#>>>数据类型('uint16')
#标量类型
打印(numpy.dtype(numpy.uint16))
#>>>数据类型('uint16')
#格式化“struct”模块中的字符
打印(numpy.dtype(“H”))
#>>>数据类型('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
设置为解析/理解各种字符串。注意文档中的
字符代码
规范名称
np.ushort
也是一个函数

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)


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

您的目的是什么?所有这些工作。我只使用
np.dtype
为结构化数组创建复合数据类型。顺便说一句,
np.int
np.float
以及其他我通常使用的
np.uint16
等等,因为这些名称对我来说是最自我记录的。
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,
  ...