将 numpy 中的字节数组转换为 int32

Casting array of bytes in numpy to int32

我有一个两个字节的 numpy 数组 A,我想将其组合成一个 int32。如何进行组合数组元素以创建不同数据类型的转换?

只要字节数正确,数组可以'viewed'具有不同的数据类型。

In [265]: arr = np.array([1,11], 'ubyte')
In [266]: arr
Out[266]: array([ 1, 11], dtype=uint8)
In [267]: arr.view('i2')
Out[267]: array([2817], dtype=int16)
In [268]: arr.view('>i2')                # with different endedness
Out[268]: array([267], dtype=int16)
In [269]: arr.view('uint16')
Out[269]: array([2817], dtype=uint16)

int32 需要 4 个字节:

In [270]: arr.view('int32')
Traceback (most recent call last):
  File "<ipython-input-270-4ab2a022f898>", line 1, in <module>
    arr.view('int32')
ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.

类似地,如果字节是从字节串中获得的

In [271]: astr = arr.tobytes()
In [272]: astr
Out[272]: b'\x01\x0b'
In [273]: np.frombuffer(astr, 'uint8')
Out[273]: array([ 1, 11], dtype=uint8)
In [274]: np.frombuffer(astr, 'uint16')
Out[274]: array([2817], dtype=uint16)
In [275]: np.frombuffer(astr, '<i2')
Out[275]: array([2817], dtype=int16)
In [276]: np.frombuffer(astr, '>i2')
Out[276]: array([267], dtype=int16)

使用复合数据类型查看

In [279]: arr.view('b')
Out[279]: array([ 1, 11], dtype=int8)
In [280]: arr.view('b,b')
Out[280]: array([(1, 11)], dtype=[('f0', 'i1'), ('f1', 'i1')])

这样看后形状可能需要调整。