[英]Python: unpacking string of integers to complex numbers
有沒有更快的方法將整數緩沖區讀取到復數數組?
這很好用(如果緩沖區帶有浮點數):
import numpy, struct
binary_string = struct.pack('2f', 1,2)
print numpy.frombuffer(binary_string, dtype=numpy.complex64)
# [ 1. + 2.j]
但是,如果讀取的緩沖區帶有整數,則會出現問題:
import numpy, struct
binary_string = struct.pack('2i', 1,2)
print numpy.frombuffer(binary_string, dtype=numpy.complex64)
# [ 1.40129846e-45 +2.80259693e-45j]
所以,除了切片,我找不到任何更快的方法來轉換它:
import numpy, struct
#for int32
binary_string = struct.pack('2i', 1,2)
ints = numpy.frombuffer(binary_string, dtype=numpy.int32)
print ints[::2] + 1j*ints[1::2]
# [ 1. + 2.j]
#for int16
binary_string = struct.pack('2H', 1,2)
ints = numpy.frombuffer(binary_string, dtype=numpy.int16)
print ints[::2] + 1j*ints[1::2]
# [ 1. + 2.j]
另外,是否存在“帶整數的復數”數據類型,因此結果可能類似於:
[1 + 2j]
謝謝。
對於包含4字節整數的字符串,可以使用:
In [35]: np.frombuffer(struct.pack('2i', 1,2), dtype='i4').astype(np.float32).view(np.complex64)
Out[35]: array([ 1.+2.j], dtype=complex64)
對於包含2字節整數的字符串,可以使用:
In [34]: np.frombuffer(struct.pack('2H', 1,2), dtype='i2').astype(np.float32).view(np.complex64)
Out[34]: array([ 1.+2.j], dtype=complex64)
這里的想法是讓np.frombuffer
使用適合於字符串的整數np.frombuffer
讀取字符串。 然后使用astype
保留整數值,但將基礎表示形式更改為float32
。 然后使用view
將基礎數據重新解釋為complex64
(因此,每兩個float32
都被視為一個complex64
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.