Search code examples
pythonpython-2.7astropy

How to write to astropy Table object values with fix number after the decimal mark?


How can I keep the format in which values are being written to an astropy Table object, and when I write the table to a file?

I am performing calculations over data that I take from a txt file that has values in this form:

3.160792680383711552e-04    9.180738349762776473e-02    7.997959651731425081e-05    9.978300086189421103e-01

Then I read those values, add another column that is my calculation based on the values of each row, and I want to write them back to a file, so the file that I write will have the same columns as the old file with another column that is the values that I calculated. But when I try to do it it changes the format in which those values are written to be:

0.000316079268038   0.0918073834976   7.99795965173e-05   0.997830008619 

Solution

  • Set the column format specifier:

    http://astropy.readthedocs.org/en/v0.3/table/construct_table.html#format-specifier

    >>> from astropy.table import Table
    >>> t = Table([[1.0]], names=['a'])
    >>> t['a'].format = '%.16e'
    >>> t.write(sys.stdout, format='ascii')
    a
    1.0000000000000000e+00