Joe*_*Joe 5 python arrays numpy complex-numbers
我知道,如果我想用 numpy 保存和加载复数数组,我可以使用此处描述的方法:How to save and load an array of complexnumbers using numpy.savetxt? 。
然而,假设有人不知道这一点并numbers
用numpy.savetxt("numbers.txt",numbers
) 保存了他们的数组,生成一个包含以下形式条目的文件
(0.000000000000000000e+00+-2.691033635430225765e-02j) .
Run Code Online (Sandbox Code Playgroud)
在这种情况下
numbers_load = numpy.loadtxt("numbers.txt").view(complex)
Run Code Online (Sandbox Code Playgroud)
可以预见的是,将会失败
ValueError: could not convert string to float: (0.000000000000000000e+00+-2.691033635430225765e-02j) .
Run Code Online (Sandbox Code Playgroud)
从该文件中提取复数的简单方法是什么(而不生成它的不同版本)?
小智 8
指定数据类型,例如:
np.loadtxt("numbers.txt", dtype=np.complex_)
Run Code Online (Sandbox Code Playgroud)
对我有用。
在保存数组之前,您应该将.view(float)
其转换为 s 数组float
,然后在加载时将 s.view(complex)
转换float
回complex
数字。
In [1]: import numpy as np
In [2]: A = np.array([1+2j, 2+5j, 3-4j, -3+1j])
In [3]: A.view(float)
Out[3]: array([ 1., 2., 2., 5., 3., -4., -3., 1.])
In [4]: np.savetxt("numbers.txt", A.view(float))
In [5]: np.loadtxt("numbers.txt")
Out[5]: array([ 1., 2., 2., 5., 3., -4., -3., 1.])
In [6]: np.loadtxt("numbers.txt").view(complex)
Out[6]: array([ 1.+2.j, 2.+5.j, 3.-4.j, -3.+1.j])
Run Code Online (Sandbox Code Playgroud)