使用PyFITS向FITS表添加列

3 投票
2 回答
3260 浏览
提问于 2025-04-18 16:33

假设我有一个fits文件,它里面有一个扩展,数据是一个包含两列的表格,每列有100个元素。

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

现在我想在我的表格中添加一个新列,叫做data['field3'],这个新列也是一个包含100个元素的数组。

我该怎么做呢?

2 个回答

0

@Cehem的回答很正确。不过我想补充一下,Astropy有一个更好用的通用表格接口,你可能会觉得使用起来更简单(比如在插入列等情况下)。

Astropy在astropy.io.fits模块中集成了PyFITS。不过,由于你也可以使用更好的表格接口,你可以像这样将大部分FITS表格读入Astropy的表格类:

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

就这样。你也可以把表格写回到FITS文件中。虽然目前这并不支持所有类型的FITS表格,但大部分都可以使用——未来会支持所有类型。

1

正如Iguananaut所提到的,答案可以在这里找到:http://pyfits.readthedocs.org/en/latest/users_guide/users_table.html#merging-tables。不过为了标记这个问题为已回答:

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')

撰写回答