numpy.genfromtxt 为带负号的复数给出 nan?

numpy.genfromtxt give nan for complex numbers with minus signs?

我在文件中有一些复数,由 np.savetxt():

编写
(8.67272e-09+-1.64817e-07j)
(2.31263e-08+1.11916e-07j)
(9.73642e-08+-7.98195e-08j)
(1.05448e-07+7.00151e-08j)

这在文件 "test.txt" 中。 当我使用`np.genfromtxt('test.txt', dtype=complex) 时,我得到:

                nan +0.00000000e+00j,
     2.31263000e-08 +1.11916000e-07j,
                nan +0.00000000e+00j,
     1.05448000e-07 +7.00151000e-08j,

这是一个错误,还是我可以做些什么来避免从负数中得到 nan

这是a bug that has been reported on the numpy github repository。问题是 savetxt 写入的字符串在虚数部分为负数时包含多余的 '+''+' 从 Python 的角度来看是无关紧要的:

In [95]: complex('1+-2j')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-95-56afbb08ca8f> in <module>()
----> 1 complex('1+-2j')

ValueError: complex() arg is a malformed string

请注意 1+-2j 是一个有效的 Python 表达式 。这建议在 genfromtxt 中使用转换器来计算表达式。

例如,这是一个复杂数组 a:

In [109]: a
Out[109]: array([1.0-1.j , 2.0+2.5j, 1.0-3.j , 4.5+0.j ])

a 保存到 foo.txt:

In [110]: np.savetxt('foo.txt', a, fmt='%.2e')

In [111]: !cat foo.txt
 (1.00e+00+-1.00e+00j)
 (2.00e+00+2.50e+00j)
 (1.00e+00+-3.00e+00j)
 (4.50e+00+0.00e+00j)

使用genfromtxt读回数据。对于转换器,我将使用 ast.literal_eval:

In [112]: import ast

In [113]: np.genfromtxt('foo.txt', dtype=np.complex128, converters={0: lambda s: ast.literal_eval(s.decode())})
Out[113]: array([1.0-1.j , 2.0+2.5j, 1.0-3.j , 4.5+0.j ])

或者,您可以使用转换器将出现的 '+-' 替换为 '-':

In [117]: np.genfromtxt('foo.txt', dtype=np.complex128, converters={0: lambda s: complex(s.decode().replace('+-', '-'))})
Out[117]: array([1.0-1.j , 2.0+2.5j, 1.0-3.j , 4.5+0.j ])