使用numpy读取Fortran格式化的小浮点文件

时间:2015-12-31 10:35:06

标签: python numpy floating-point fortran

我正在尝试读取由Fortran程序编写的数据文件,其中每隔一段时间就有一个非常小的浮点数,如0.3299880-104。错误消息是:

>np.loadtxt(filename, usecols = (1,))

  File "/home/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 928, in loadtxt
    items = [conv(val) for (conv, val) in zip(converters, vals)]

  File "/home/anaconda2/lib/python2.7/site-packages/numpy/lib/npyio.py", line 659, in floatconv
    return float(x)

ValueError: invalid literal for float(): 0.3299880-104

我能做些什么让Numpy能够读取这个数据文件吗?

1 个答案:

答案 0 :(得分:2)

在评论中提到 @agentp ,一种方法是使用converters=参数np.genfromtxt来插入e字符,然后再转换为浮点数:

import numpy as np

# some example strings
strings = "0.3299880-104 0.3299880+104 0.3299880"

# create a "dummy file" (see http://stackoverflow.com/a/11970414/1461210)
try:
    from StringIO import StringIO     # Python2
    f = StringIO(strings)
except ImportError:
    from io import BytesIO            # Python3
    f = BytesIO(strings.encode())

c = lambda s: float(s.decode().replace('+', 'e').replace('-', 'e-'))

data = np.genfromtxt(f, converters=dict(zip(range(3), [c]*3)))

print(repr(data))
# array([  3.29988000e-105,   3.29988000e+103,   3.29988000e-001])