Search code examples
pythondataframeformattingnumber-formattingastropy

Formatting with astropy.io.ascii


I have an AstroPy Table of data:

>>> data

 ra           dec          redshift ... yMeanPSFMag       yMeanPSFMagErr
 ------------ ------------ -------- ... ----------------- --------------------

 0.34011348  26.83588138     5.75 ...  19.49519920349121   0.03307399898767471
 0.66411726  25.84304425     5.82 ...  19.45319938659668   0.04351300001144409
 1.4680833   -0.1154999      5.85 ...  20.118600845336914  0.18635299801826477
 2.10739     -6.43456        5.93 ...  20.439899444580078  0.16982899606227875

and I'd simply like to output this in a control formatted way:

>>>  df = data['ra', 'dec']
>>>  ascii.write(df, 'temp.dat', overwrite=True, formats="{df['ra']:%3.1f, df['dec']:%8.3f}")

and I get a:

TypeError: string indices must be integers

I had a look at this package but can't see anything directly useful.


Solution

  • I do this fairly often. To stay close to what you've written:

    df = data['ra', 'dec'] 
    ascii.write(df, 'temp.dat', overwrite=True, formats={'ra':'%3.1f','dec':'%8.3f'})
    

    or my preferred way to do this would be

    aformats = ['%.1f','%.3f']
    oformats = dict(zip(df.colnames, aformats))
    ascii.write(df, 'temp.dat', overwrite=True, formats=oformats)
    

    bc specifying the total digits isn't often necessary.