Python:将整数字符串解包为复数

时间:2016-01-08 11:04:50

标签: python numpy

是否有更快的方法将整数缓冲区读取到复数数组?

这很好(如果缓冲区有浮点数):

import numpy, struct
binary_string = struct.pack('2f', 1,2)
print numpy.frombuffer(binary_string, dtype=numpy.complex64)
# [ 1. + 2.j]

但是,如果readed缓冲区是整数,则存在一个问题:

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]

感谢。

1 个答案:

答案 0 :(得分:1)

对于打包为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使用适合字符串的整数dtype读取字符串。然后使用astype保留整数,但将基础表示更改为float32。然后使用view将基础数据重新解释为complex64 s(因此每两个float32被视为一个complex64。)