Python:将浮点字符串解包为复数

时间:2013-03-06 10:08:53

标签: python arrays struct

我对编码很新,我正在从二进制文件中读取信号。数据定向为两个4字节浮点数,构成一个复数,这可以重复达到1500个条目

我一直在使用for循环来提取数据并将复数附加到数组

for x in range(dimX):
    for y in range(dimY):
        complexlist=[]
        #2 floats, each 4 bytes, is one complex number
        trace=stream.readBytes(8*dimZ)
        #Unpack as list of floats
        floatlist=struct.unpack("f"*2*dimZ,trace)
        for i in range(0,len(floatlist)-1,2):
            complexlist.append(complex(floatlist[i],floatlist[i+1]))        
        data[x][y]=np.array(complexlist)

其中dimX可能是数千,DimY通常<30且dimZ <1500

但是在大​​文件中这是非常缓慢的

有没有办法读取整个跟踪的缓冲区并直接解压缩到复数数组?

1 个答案:

答案 0 :(得分:2)

是的,有。您可以跳过python的复杂类型的步骤,因为在内部,numpy将n复数数组表示为2n浮点数组。

以下是REPL中一个简单的例子:

>>> import numpy as np
>>> a = np.array([1.,2.,3.,4.])
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.dtype
dtype('float64')
>>> a.dtype = complex
>>> a
array([ 1.+2.j,  3.+4.j])
>>> 

请注意,如果初始数组的dtype不是float,则此方法无效。

>>> a = np.array([1,2,3,4])
>>> a
array([1, 2, 3, 4])
>>> a.dtype
dtype('int64')
>>> a.dtype = complex
>>> a
array([  4.94065646e-324 +9.88131292e-324j,
         1.48219694e-323 +1.97626258e-323j])
>>>

在你的情况下。您想要的dtype是np.dtype('complex64'),因为每个复数都是64位(2 * 4 * 8)。

for x in range(dimX):
    for y in range(dimY):
        #2 floats, each 4 bytes, is one complex number
        trace=stream.readBytes(8*dimZ)
        a = np.frombuffer(trace,dtype=np.dtype('complex64'))
        data[x][y] = a

这应该可以加快你的速度。以下是REPL中numpy.frombuffer()如何工作

的示例
>>> binary_string = struct.pack('2f', 1,2)
>>> binary_string
'\x00\x00\x80?\x00\x00\x00@'
>>> numpy.frombuffer(binary_string, dtype=np.dtype('complex64'))
array([ 1.+2.j], dtype=complex64)
>>> 

编辑:我不知道numpy.frombuffer()的存在。所以我创建了一个字符数组,然后更改dtype以获得相同的效果。谢谢@wim

编辑2:

至于进一步的速度优化,你可能会通过使用列表解析而不是显式的for循环来提升性能。

for x in range(dimX):
    data[x] = [np.frombuffer(stream.readBytes(8*dimZ), dtype=np.dtype('complex64')) for y in range(dimY)]

然后升级:

data = [[np.frombuffer(stream.readBytes(8*dimZ), dtype=np.dtype('complex64'))
         for y in range(dimY)]
         for x in range(dimX)]