Search code examples
python-3.xastropyfits

Astropy Fits: How to write out a table with rows sliced out?


I'm currently working with some fits tables and I'm having trouble with outputting in Astropy.io.fits. Essentially, I am slicing out a bunch of rows that have data for objects I'm not interested in, but when I save the new table all of those rows have magically reappeared.

For example:

import astropy.io.fits as fits
import numpy as np

hdu = fits.open('some_fits_file.fits')[1].data

sample_slice = [True True True False False True]

hdu_sliced = hdu[sample_slice]

Now my naive mind expects that "hdu" has 6 rows and hdu_sliced has 4 rows, which is what you would get if you used np.size(). So if I save hdu_sliced, the new fits file will also have 4 rows:

new_hdu = fits.BinTableHDU.from_columns(fits.ColDefs(hdu_sliced.columns))

new_hdu.writeto('new_fits_file.fits')

np.size(hdu3)
6

So those two rows that I got rid of with the slice are for some reason not actually being removed from the table and the outputted file is just the same as the original file.

How do I delete the rows I don't want from the table and then output that new data to a new file?

Cheers, Ashley


Solution

  • If you want to stick to using FITS_rec, you can try the following, which seems to be a workaround:

    new_hdu = fits.BinTableHDU.from_columns(hdu_sliced._get_raw_data())