Aug 7, 2023

How to use Python's Astropy library to manipulate FITS files

How to use Python's Astropy library to manipulate FITS files

How to use Python's Astropy library to manipulate FITS files

1. Import the relevant module and open a FITS file:

from astropy.io import fits
hdul = fits.open('file.fits')

2. Display file content information:

hdul.info()

3. Accessing individual Header/Data Units (HDUs):

hdu = hdul[0]  # Access the first HDU

4. Access header and data from the HDU:

header = hdu.header
data = hdu.data

5. Modifying the data and header:

hdu.data = hdu.data * 2  # Multiply all data by 2
hdu.header['OBJECT'] = 'New_Object'  # Modify a header value

6. Access a specific keyword from the header:

object_name = header['OBJECT']  # Access a specific keyword

7. Add a new keyword to the header:

header['NEWKEY'] = (42, 'Demo keyword')  # Add a new keyword with a comment

8. Delete a keyword from the header:

del header['NEWKEY']  # Delete the keyword

9. Iterate over all keywords in the header:

for keyword in header:
    print(header[keyword])

10. Create a new HDU with your data and header:

from astropy.io.fits import PrimaryHDU
new_hdu = PrimaryHDU(data=hdu.data, header=hdu.header)

11. Append new HDU to the HDU list:

hdul.append(new_hdu)

12. Save the changes to a new FITS file:

hdul.writeto('newfile.fits', overwrite=True)

The overwrite=True argument is used to overwrite the output file if it already exists.

13. Slice the data (useful for large datasets):

Astropy supports slicing of FITS files without loading the entire file into memory:

slice = hdul[0].section[10:20, 10:20]  # Extract a 10x10 slice from the image

14. Close the FITS file:

hdul.close()