【问题标题】:Python: unpacking string of integers to complex numbersPython:将整数字符串解包为复数
【发布时间】:2016-01-08 11:04:50
【问题描述】:

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

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

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]

谢谢。

【问题讨论】:

  • 关于复数部分,可以查看thread
  • “更快”几乎从来都不是正确的目标。
  • “更快”还可以,但是除了切片之外,还有一些“原生”的 numpy 方法吗?

标签: python numpy


【解决方案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 保留整数,但将底层表示更改为float32s。然后使用view 将基础数据重新解释为complex64s(因此每两个float32s 被视为一个complex64)。

【讨论】:

  • 这确实让我的脚本运行得更快(大约 40%),而且它是切片以外的本地方法。谢谢。谢谢。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多