NeStack
NeStack

Reputation: 2014

How to convert .fits file/ astropy table to pandas df and reverse?

I need to frequently convert pandas df to .fits files and also the reverse - I am given .fits files for which is easier for me to process them as pandas dfs. What is the most straightforward way for doing the conversions between these file types?

Upvotes: 4

Views: 2860

Answers (1)

NeStack
NeStack

Reputation: 2014

# 1.)  how to convert a pandas df 
# (or almost any ascii data file) to astropy table
# and save the table as .fits file

from astropy.table import Table
import pandas as pd

df = pd.read_csv('some_file.dat', delim_whitespace=True, skiprows=7, names=['A', 'B', 'C'])

t = Table.from_pandas(df)
t.write('some_file.fits')




# 2.)  how to convert a fits file (or astropy table) to pandas df

dat = Table.read('some_file.fits')
df = dat.to_pandas()



# 3.)  it is like 1.) but without a df as intermediate step - 
# how to read a csv/ascii file directly as astropy table
# and save it as .fits   

table = Table.read('some_file.dat', format='ascii.tab')
table.write('some_file.fits', overwrite=True)

Upvotes: 3

Related Questions