如何使用numpy.savetxt保存和加载复数数组? [英] How to save and load an array of complex numbers using numpy.savetxt?
问题描述
我想使用 numpy.savetxt()
来将复数数组保存到文本文件.问题:
I want to use numpy.savetxt()
to save an array of complex numbers to a text file. Problems:
- 如果使用默认格式字符串保存复杂数组,则虚部将被丢弃.
- 如果使用
fmt='%s'
,那么除非指定dtype=complex, converters={0: lambda s: complex(s)}
,否则numpy.loadtxt()
无法加载它.即使那样,即使数组中存在NaN,加载仍然会失败.
- If you save the complex array with the default format string, the imaginary part is discarded.
- If you use
fmt='%s'
, thennumpy.loadtxt()
can't load it unless you specifydtype=complex, converters={0: lambda s: complex(s)}
. Even then, if there are NaN's in the array, loading still fails.
好像有人问过这个多个在Numpy邮件列表上时间甚至提交了错误,但没有得到回应.在我自己整理东西之前,有没有一种规范的方法可以做到这一点?
It looks like someone has inquired about this multiple times on the Numpy mailing list and even filed a bug, but has not gotten a response. Before I put something together myself, is there a canonical way to do this?
推荐答案
它更加简单,并保存了一些临时数组,以将数组重新解释为真实数组.
It's easier and saves a few temporary arrays to just reinterpret the array as a real array.
保存:
numpy.savetxt('outfile.txt', array.view(float))
正在加载:
array = numpy.loadtxt('outfile.txt').view(complex)
如果您希望在文件的同一行上包含实部和虚部,则可以使用
If you prefer to have real and imaginary part on the same line in the file, you can use
numpy.savetxt('outfile.txt', array.view(float).reshape(-1, 2))
或
array = numpy.loadtxt('outfile.txt').view(complex).reshape(-1)
分别.
(请注意,view()
和reshape()
均不会复制该数组,它只会以不同的方式重新解释相同的数据.)
(Note that neither view()
nor reshape()
copies the array -- it will just reinterpret the same data in a different way.)
提问者的附录:
如果要在同一文件中保存多个复杂数组,可以这样做:
If you want to save more than one complex array in the same file, you can do it like so:
numpy.savetxt('outfile.txt', numpy.column_stack([
array1.view(float).reshape(-1, 2),
array2.view(float).reshape(-1, 2),
]))
array1, array2 = numpy.loadtxt('outfile.txt', unpack=True).view(complex)
重塑是必要的,因为numpy.view()
不适用于跨步数组.
The reshaping is necessary because numpy.view()
doesn't operate on strided arrays.
这篇关于如何使用numpy.savetxt保存和加载复数数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!