2012-11-19 4 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

관련 문제