将二进制字符串转换为numpy数组

2024-06-28 20:42:58 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有字符串:

my_data = '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'

我得到它的地方是不相关的,但是为了得到具体的东西,假设我是从二进制文件中读取的。

我知道我的字符串是4(4字节)浮点的二进制表示。我想把那些漂浮物做成核阵列。我可以做:

import struct
import numpy as np
tple = struct.unpack( '4f', my_data )
my_array = np.array( tple, dtype=np.float32 )

但是创建中间元组似乎很傻。有没有办法在不创建中间元组的情况下执行此操作?

编辑

我还希望能够以这样一种方式构造数组,即可以指定字符串的endianness。


Tags: 文件字符串importdata字节my地方np
1条回答
网友
1楼 · 发布于 2024-06-28 20:42:58
>>> np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='<f4') # or dtype=np.dtype('<f4'), or np.float32 on a little-endian system (which most computers are these days)
array([ 1.,  2.,  3.,  4.], dtype=float32)

或者,如果你想要大端:

>>> np.fromstring(b'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4') # or dtype=np.dtype('>f4'), or np.float32  on a big-endian system
array([  4.60060299e-41,   8.96831017e-44,   2.30485571e-41,
         4.60074312e-41], dtype=float32)

当然,在Python 3之前不需要b

事实上,如果实际使用二进制文件从中加载数据,甚至可以跳过using-a-string步骤,直接使用numpy.fromfile()从文件中加载数据。

还有,dtype引用,以防万一:http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

相关问题 更多 >