Unable to instantiate astropy.io.fits.TableHDU class

I’m attempting to instantiate a simple ASCII HDU, but it doesn’t seem to work the same way as astropy.io .fits.BinTableHDU . For example, this works just fine:

from astropy.table import Table
from astropy.io.fits import TableHDU, BinTableHDU
t1 = Table()
t1['col1'] = ['test 1', 'test 2', 'test 3']
t1['col2'] = [1, 2, 3]
hdu = BinTableHDU(data=t1, name='MY_BINARY_HDU')
hdu.writeto('binary_test.fits', overwrite=True)

but attempting to do the same thing as an ASCII table doesn’t:

t2 = Table()
t2['col1'] = ['test 1', 'test 2', 'test 3']
t2['col2'] = [1, 2, 3]

hdu = TableHDU(data=t2, name='MY_ASCII_HDU')
hdu.writeto('ascii_test.fits', overwrite=True)

yielding this error:

TypeError: Table data has incorrect type.

Am I doing something wrong?

1 Like

It’s not possible to build a TableHDU from a Table, so you have to build it directly with the io.fits API: Less Familiar Objects — Astropy v5.3.dev0

1 Like

In your example you might also instantiate it directly from the previously written table

with fits.open('binary_test.fits') as hdulist:
    hdu = TableHDU(data=hdulist[1].data, name='MY_ASCII_HDU')

but that is probably not very helpful in the general case.
The docstring for that class is a bit confusing as there seems to be almost no other way to instantiate it through the data parameter, but the ASCII table format is rarely used.

1 Like

TableHDU.from_columns as explained in the link above is probably the most useful way to create it; it should also directly handle numpy structured arrays, if that is more convenient.

t2 = np.recarray(3, dtype=[('col1', 'S6'), ('col2', 'i4')])
t2['col1'] = ['test 1', 'test 2', 'test 3']
t2['col2'] = np.arange(1, 4)

hdu = TableHDU.from_columns(t2, name='MY_ASCII_HDU')
1 Like

Thanks, this is a huge help. I think this is exactly what I was looking for. It would be nice however if astropy used the same interface for both kinds of tables, that would help to encapsulate many of these details. Although… perhaps it’s better to use the fits Column method in both instances?

Thanks dhomeier, this also works great, as does the suggestion by saimn. Thanks!

The Table to TableHDU interface doesn’t exist because ASCII table are not so common, binary table are much more used.
So on one side there is the API from astropy.io.fits, for ASCII and binary tables :

And then there is astropy.table.Table, which can currently be converted only to a io.fits binary table (BinTableHDU).