Reading & Writing (table data) Fits Files in Python

This is one technique of writing arrays to fits files and correspondingly accessing those arrays. I create a fits file where each column of data corresponds to an array. In this example I have three ndarrays (wv_full_test,  fx_full_test, and (fx_full_test*.1).

(1)  Writing table data arrays to a fits file:
$import pyfits

$col1 = pyfits.Column(name = ‘wave’, format = ‘D’, array = wv_full_test)
$col2 = pyfits.Column(name = ‘fx’, format = ‘D’, array = fx_full_test)
$col3 = pyfits.Column(name = ‘fx_error’, format = ‘D’, array = (wv_full_test*.1))

$cols = pyfits.ColDefs([col1, col2, col3])
$tbhdu = pyfits.new_table(cols)
$hdu = pyfits.PrimaryHDU()
$thdulist = pyfits.HDUList([hdu, tbhdu])

(2) Reading fits files into table data arrays:
$input = pyfits.core.getdata(‘filename.fits’, 1)

(3) To access each individual array:
$wavelength_array = input.field(‘wave’)
$fx_array = input.field(‘fx’)
$fx_error_array = input.field(‘fx’)

For more information take a look at the Pyfits Handbook



Rebin Numpy Arrays in Python

I’m currently working to determine radial velocities of suspected young brown dwarfs. I’m working with high resolution optical spectra collected from the MIKE Spectrograph on Magellan II. Through this process I’ve gained a much better understanding for data analysis and reduction in Python.

One such helpful tool I recently discovered in Python is how to rebin numpy arrays. Vivienne and I are cross-correlating two stellar spectrums to determine the relative pixel shifts between the two. These pixel shifts correspond to wavelength shifts of the emitted stellar light due to the doppler effect. In order to gain a more precise measurement of the relative pixel shift I rebinned the data. Data rebinning is useful when you want to reduce or increase the amount of data you’re working with, without losing important information. I rebinned my data from a precision of 1 pixel to .1 pixel.

Below is a plot of the Rebinned (blue) and Original (red) Flux & Wavelength Data.

I wrote a script in Python to rebin the data. The useful commands are:

#convert wavelength & flux into from lists to arrays called wave_array & fx_array
wave_array = numpy.asarray(wave_nz, dtype = float)
fx_array = numpy.asarray(fx_nz, dtype = float)

#rebin data array by a factor of 10.
wv_full_test = scipy.ndimage.interpolation.zoom(wave_array, 10)
fx_full_test = scipy.ndimage.interpolation.zoom(fx_array, 10)