2012-11-19 51 views
2

在Numpy中,我需要将一些二进制数据解压缩为一个变量。在过去,我一直使用Numpy中的'fromstring'函数解压它,并提取第一个元素。有没有一种方法可以直接将二进制数据解压缩为Numpy类型,并避免创建一个我几乎忽略的Numpy数组的开销?Numpy将二进制字符串解压缩为一个变量

这是目前我做的:

>>> int_type 
dtype('uint32') 
>>> bin_data = '\x1a\x2b\x3c\x4d' 
>>> value = numpy.fromstring(bin_data, dtype = int_type)[0] 
>>> print type(value), value 
<type 'numpy.uint32'> 1295788826 

我愿做这样的事情:

>>> value = int_type.fromstring(bin_data) 
>>> print type(value), value 
<type 'numpy.uint32'> 1295788826 

回答

2
In [16]: import struct 

In [17]: bin_data = '\x1a\x2b\x3c\x4d' 

In [18]: value, = struct.unpack('<I', bin_data) 

In [19]: value 
Out[19]: 1295788826 
2
>>> np.frombuffer(bin_data, dtype=np.uint32) 
array([1295788826], dtype=uint32) 

虽然这将创建一个阵列结构,实际数据在字符串和数组之间共享:

>>> x = np.frombuffer(bin_data, dtype=np.uint32) 
>>> x[0] = 1 
------------------------------------------------------------ 
Traceback (most recent call last): 
    File "<ipython console>", line 1, in <module> 
RuntimeError: array is not writeable 

fromstring会复制它。

+0

有趣的是,thx – Qlaus