numpy.fromstring 中的 ValueError

Zuh*_*uhi 5 python numpy

我想将这些字符串值转换为 int16 数据类型的 numpy 数组

import numpy as np
raw=b''
w="\x01\x02 \x01\x02"
w1="\x01\x03 \x04"
p=w.replace(" ", "")
w1=w1.replace(" ","")
raw +=p
raw +=w1
results = np.fromstring(raw, dtype=np.uint16)
print results
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

>File "prj1.py", line 11, in <module>
> results = np.fromstring(raw, dtype=np.uint16)
>ValueError: string size must be a multiple of element size
Run Code Online (Sandbox Code Playgroud)

如何将这些字符串转换为数据类型为 int16 的 numpy 数组?

Tho*_*ühn 5

正如错误消息所述,如果fromstring输入二进制输入数据,则数据长度必须是元素大小的倍数。文档中也说明了这一点。在您的例子中,元素大小为 2,因为 auint16由两个字节组成。但是,在第二个字符串 中w1,您仅提供 1 个字节。解决此问题的一种方法是向较小的数字添加前导零:

import numpy as np
raw=b''
w="\x01\x02 \x01\x02"
w1="\x01\x03 \x04"
elements=w.split(' ')+w1.split(' ')
raw=b''.join(['\x00'+e if len(e)==1 else e for e in elements ])
results = np.fromstring(raw, dtype=np.uint16)
print results
Run Code Online (Sandbox Code Playgroud)

这输出:

[ 513  513  769 1024]
Run Code Online (Sandbox Code Playgroud)

对我来说这个结果是令人惊讶的。显然,字节是从左到右(最小到最大)读取的。我不知道这是特定于平台的(我在osx)还是总是像这样numpy。无论如何,如果您想要的字节顺序是从右到左,您可以颠倒顺序,如下所示:

raw2=b''.join([e+'\x00' if len(e)==1 else e[1]+e[0] for e in elements])
results2 = np.fromstring(raw2, dtype=np.uint16)
print results2
Run Code Online (Sandbox Code Playgroud)

结果是:

[258 258 259   4]
Run Code Online (Sandbox Code Playgroud)