0

I'm attempting to read the data from a FITS file using the astropy module fits and then standard numpy array handling. However, for some reason I am receiving the following error:

IndexError: too many indices

This is the code that I am using:

from astropy.io import fits
import matplotlib.pyplot as plt

hdulist = fits.open('/Users/iMacHome/Downloads/spec-1959-53440-0605.fits')
hdu     = hdulist[1]
data    = hdu.data
flux    = data[:, 1] 

^ Error Traceback to the flux = data[:, 1] line.

loglam  = data[:, 2]

This may be a question that perhaps astronomers could answer (or, specifically, astronomers familiar with .fits files from the SDSS), but I welcome the input from numpy and python users!

GCien
  • 2,221
  • 6
  • 30
  • 56

1 Answers1

1

I have just had the following answer from the SDSS help desk:

Replace:

flux   = data[:,0]
loglam = data[:,1]

with

flux   = data['flux']
loglam = data['loglam']

This is the correct way to access fields in a Numpy record array.

Iguananaut
  • 21,810
  • 5
  • 50
  • 63
GCien
  • 2,221
  • 6
  • 30
  • 56
  • 1
    If this works, it's probably a good idea to go ahead and accept your own answer. – ThatOneDude Aug 26 '14 at 20:06
  • I can only do this in 2 days time, apparently. – GCien Aug 26 '14 at 20:17
  • It looks like `data` is a `BinTableHDU`, not an `ImageHDU`, which is why using multiple indices failed. If you look at the `repr` of the object, it will show you that there are multiple `dtypes`: `dtype=[('flux', '>f4'), ('loglam', '>f4'), ('ivar', '>f4'), ('and_mask', '>i4'), ('or_mask', '>i4'), ('wdisp', '>f4'), ('sky', '>f4'), ('model', '>f4')]`. You can also use `data.dtype.names` – keflavich Aug 27 '14 at 05:41
  • 1
    It may be useful, if you're not sure what's going on with a FITS file, to use `hdulist.info()` to print basic statistics on the file, you would then find that this is a table not a basic array. And as @keflavich mentioned above if you print the data array itself you can also see that it is a table (or multi-field array). See also http://docs.astropy.org/en/stable/io/fits/usage/table.html#table-data-as-a-record-array – Iguananaut Aug 27 '14 at 15:01
  • 1
    FWIW I also submitted a slight edit to your answer to clarify that the column-name indexing is the correct way to access fields in a multi-field Numpy array. – Iguananaut Aug 27 '14 at 15:04