Adding columns to a FITS table with PyFITS

3.2k Views Asked by At

Let's assume I have a fits file with one extension, and the data consists of a table of two columns with 100 elements each

data = pyfits.open('path2myfile')[1].data
head = pyfits.open('path2myfile')[1].header
print data['field1'] # print an array with 100 elements
print data['field2'] # print another array with 100 elements

Now I want to add to my table a new column, let's say data['field3'], which is another array of 100 elements.

How exactly do I do that ?

2

There are 2 best solutions below

0
On BEST ANSWER

As Iguananaut indicated, the answer can be found here : http://pyfits.readthedocs.org/en/latest/users_guide/users_table.html#merging-tables But just to mark this question as answered:

cols = [] 
cols.append(
    pyfits.Column(name='field3', format='D', array= arrayContainingTheData)
    )
orig_cols = data.columns
new_cols = pyfits.ColDefs(cols)
hdu = pyfits.BinTableHDU.from_columns(orig_cols + new_cols)
hdu.writeto('newtable.fits')
0
On

@Cehem's answer is right on. But I just wanted to add that Astropy has a much better general purpose Table interface that you might find easier to use (for inserting columns among other use cases).

Astropy incorporates PyFITS in the astropy.io.fits module. But since you also have access to the better Table interface you can read most FITS tables into the Astropy table class like so:

>>> from astropy.table import Table
>>> table = Table.read('path/to/fits_file.fits')

And that's it. You can also write the table back out to a FITS file. Granted, this currently does not support all types of FITS tables, but it will work for most--and in the future all.