使用PyFITS向FITS表中添加列

3

假设我有一个包含一个扩展名的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个元素的数组。

我应该如何实现?


1
在仔细阅读了您的问题几次后,我意识到您实际上拥有的是一个 FITS 表格,您想要添加一列。请参见:http://pyfits.readthedocs.org/en/latest/users_guide/users_table.html#merging-tables - Iguananaut
啊,谢谢,我之前没有用对词汇。这就解决了! - Cehem
2个回答

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

0

@Cehem的回答是正确的。但我想补充一点,Astropy有一个更好的通用Table接口,你可能会发现更容易使用(例如插入列等其他用例)。

Astropy将PyFITS集成在astropy.io.fits模块中。但由于您还可以访问更好的Table接口,因此您可以像这样将大多数FITS表读入Astropy表类:

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

就是这样。您还可以将表格写回到FITS文件中。 当然,目前这并不支持所有类型的FITS表格,但它适用于大多数情况-而且在未来会支持所有类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接