0

I have a fortran formatted txt file with numbers like this 0.755473D-08.

if I use np.genfromtxt(data,dtype=None), it shows b'0.755473D-08'. How can I can I get rid of b?

kinder chen
  • 1,371
  • 5
  • 15
  • 25

1 Answers1

1
In [315]: txt = '''0.755473D-08
     ...: 0.755473D-08
     ...: 0.755473D-08'''
In [316]: np.genfromtxt(txt.splitlines())
Out[316]: array([nan, nan, nan])
In [317]: np.genfromtxt(txt.splitlines(),dtype=None)
...
Out[317]: array([b'0.755473D-08', b'0.755473D-08', b'0.755473D-08'], dtype='|S12')

Using String replace:

In [319]: txt.replace('D','e')
Out[319]: '0.755473e-08\n0.755473e-08\n0.755473e-08'
In [320]: np.genfromtxt(_.splitlines())
Out[320]: array([7.55473e-09, 7.55473e-09, 7.55473e-09])

That could also be done line by line (when reading from a file).

With a converter, applied to each element (column per line):

In [326]: np.genfromtxt(txt.splitlines(), converters={0:lambda x:float(x.replace('D','e'))}, encoding=None)
Out[326]: array([7.55473e-09, 7.55473e-09, 7.55473e-09])

It doesn't try to do any further dtype conversion after the converter, so I had to include the float() in the converter.

hpaulj
  • 221,503
  • 14
  • 230
  • 353