python - numpy.genfromtxt 给出带有负号的复数 nan 吗?

标签 python numpy nan genfromtxt

我的文件中有一些复数,由 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 ])

关于python - numpy.genfromtxt 给出带有负号的复数 nan 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47084008/

相关文章:

python - 将 nans 替换为移动窗口的正态分布

python - Django Rest Framework OPTIONS 操作仅显示 POST

python - PyQt : switch windows/layouts created by Qt Designer

python - Matplotlib 由于 findfont 引发警告消息 - python

python - 逐像素读取图像(ndimage/ndarray)

Python 中值滤波器应用于 3D 数组以产生 2D 结果

python - numpy 中的索引(与 max/argmax 相关)

python - Scipy 排名数据从高到低反转

python - 忽略 nan 值并执行 numpy.polyval 的函数

python - 如何将具有相同索引的多行组合在一起,并且每一行在pandas中只有一个真实值?