pythonastropyfitspyfits

Multiple Tables saved in the same .fits file


I have multiple tables created with astropy.table.Table, for example:

 from astropy.table import Table
 import numpy as np
 #table 1
 ta=Table()
 ta["test1"]=np.arange(0,100.)
 #table 2
 tb=Table()
 tb["test2"]=np.arange(0,100.)

I can save them individually to .fits files using

ta.write('table1.fits')
tb.write('table2.fits')

But I would like to have them saved to the same .fits file, each of them with a different hdu. How can I do that?


Solution

  • There's an example of how to do this here. So, you could do something like the following:

    import numpy as np
    from astropy.io import fits
    
    ta = Table()
    ta['test1'] = np.arange(0, 100.)
    col1 = fits.Column(name=ta.colnames[0], format='E', array=ta)
    
    tb = Table()
    tb['test2'] = np.arange(0, 100.)
    col2 = fits.Column(name=tb.colnames[0], format='E', array=tb)
    
    cols = fits.ColDefs([col1, col2])
    
    hdu = fits.BinTableHDU.from_columns(cols)
    hdu.writeto('table.fits')
    

    which only has one binary table HDU, but with two columns. Alternatively, to add them as separate HDUs, you could do something like

    ta = Table()
    ta['test1'] = np.arange(0, 100.)
    col1 = fits.Column(name=ta.colnames[0], format='E', array=ta)
    
    hdu1 = fits.BinTableHDU.from_columns(fits.ColDefs([col1]))
    
    tb = Table()
    tb['test2'] = np.arange(0, 100.)
    col2 = fits.Column(name=tb.colnames[0], format='E', array=tb)
    
    hdu2 = fits.BinTableHDU.from_columns(fits.ColDefs([col2]))
    
    # create a header
    hdr = fits.Header()
    hdr['Author'] = 'Me'
    primary_hdu = fits.PrimaryHDU(header=hdr)
    
    # put all the HDUs together
    hdul = fits.HDUList([primary_hdu, hdu1, hdu2])
    
    # write it out
    hdul.writeto('table.fits')