[AstroPy] Add an astropy.table.Table to a multi-extension FITS file?

Erik Bray embray at stsci.edu
Thu Dec 18 10:41:44 EST 2014


On 12/17/2014 08:55 PM, David Kirkby wrote:
> Is it possible to create a table as an astropy.table.Table and then convert it
> to an astropy.fits.io.BinTableHDU suitable for adding to the
> astropy.io.fits.HDUList of a multi-extension file?
>
> I guess that astropy.table.Table.write already implements this but I didn't see
> how to only generate a new HDU in memory with this API.

Incidentally, there is an open issue for exactly this (patches welcome :):

https://github.com/astropy/astropy/issues/3058

On 12/17/2014 11:41 PM, J. Xavier Prochaska wrote:
 > I don’t recall where I pulled this syntax, but it works fine:
 >
 >      prihdr = fits.Header()
 >      prihdu = fits.PrimaryHDU(header=prihdr)
 >
 >      #data is an astropy Table
 >      table_hdu = fits.BinTableHDU.from_columns(np.array(data.filled()))
 >
 >      thdulist = fits.HDUList([prihdu, table_hdu])
 >      thdulist.writeto(outfil,clobber=True)

Xavier's workaround is good for now.  However, there are parts of it that are 
unnecessary.  For example, creating an empty primary HDU is unnecessary unless 
you intend to put additional keyword in the primary header.  Otherwise just:

table_hdu.writeto(filename)

will suffice (no need for any of the intermediate steps).

Also I think

table_hdu = fits.BinTableHDU.from_columns(np.array(data))

is good enough in most cases.  Calling filled() is only necessary if you have 
masked data.  So really, getting a BinTableHDU from a Table boils down to the 
one line above.


Erik



More information about the AstroPy mailing list