Our first task with Python was to read a .csv
file using np.loadtxt()
.
That function has some arguments to define the dlimiter of the columns, skip rows, read commented lines, convert values while reading, etc.
However, the result is an array, without the information of the metadata that file may have included (name, units, ...).
AstroPy offers an ascii reader that improves many of these steps and provides templates to read common ascii files in astronomy.
from astropy.io import ascii
# Read a sample file: sources.dat
data = ascii.read("sources.dat")
data
Automatically, ascii.read()
has identified the header and the format of each column. The result is a Table
object, and that brings some additional properties.
# Show the info of the data read
data.info
# Get the name of the columns
data.colnames
# Get just the values of a particular column
data['obsid']
# get the first element
data['obsid', 'redshift'][0]
Astropy can read a variety of formats easily. The following example uses a quite
# Read the data from the source
table = ascii.read("ftp://cdsarc.u-strasbg.fr/pub/cats/VII/253/snrs.dat",
readme="ftp://cdsarc.u-strasbg.fr/pub/cats/VII/253/ReadMe")
# See the stats of the table
table.info('stats')
# If we want to see the first 10 entries
table[0:10]
# the units are also stored, we can extract them too
table['MajDiam'].quantity.to('rad')[0:3]
# Adding values of different columns
(table['RAh'] + table['RAm'] + table['RAs'])[0:3]
# adding values of different columns but being aware of column units
(table['RAh'].quantity + table['RAm'].quantity + table['RAs'].quantity)[0:3]
# Create a new column in the table
table['RA'] = table['RAh'].quantity + table['RAm'].quantity + table['RAs'].quantity
# Show table's new column
table['RA'][0:3]
# add a description to the new column
table['RA'].description = table['RAh'].description
# Now it does show the values
table['RA'][0:3]
# Using numpy to calculate the sin of the RA
import numpy as np
np.sin(table['RA'].quantity)
# Let's change the units...
import astropy.units as u
table['RA'].unit = u.hourangle
# does the sin now works?
np.sin(table['RA'].quantity)
the reading of the table has many properties, let's imagine the following easy example:
weather_data = """
# Country = Finland
# City = Helsinki
# Longitud = 24.9375
# Latitud = 60.170833
# Week = 32
# Year = 2015
day, precip, type
Mon,1.5,rain
Tues,,
Wed,1.1,snow
Thur,2.3,rain
Fri,0.2,
Sat,1.1,snow
Sun,5.4,snow
"""
# Read the table
weather = ascii.read(weather_data)
# Blank values are interpreted by default as bad/missing values
weather.info('stats')
# Let's define missing values for the columns we want:
weather['type'].fill_value = 'N/A'
weather['precip'].fill_value = -999
# Use filled to show the value filled.
weather.filled()
# We can see the meta as a dictionary, but not as key, value pairs
weather.meta
# To get it the header as a table
header = ascii.read(weather.meta['comments'], delimiter='=',
format='no_header', names=['key', 'val'])
print(header)
When the values are not empty, then the keyword fill_values
on read
has to be used.
VOTables are an special type of tables which should be self-consistent and can be tied to a particular scheme. This means the file will contain where the data comes from (and which query produced it) and the properties for each field, making it easier to ingest by a machine.
from astropy.io.votable import parse_single_table
# Read the example table from HELIO (hfc_ar.xml)
table = parse_single_table("hfc_ar.xml")
# See the fields of the table
table.fields
# extract one (NOAA_NUMBER) or all of the columns
NOAA = table.array['NOAA_NUMBER']
# Show the data
NOAA.data
# See the mask
NOAA.mask
# Shee the whole array.
NOAA
# Convert the table to an astropy table
asttable = table.to_table()
# See the table
asttable
# Different results because quantities are not
print(np.sin(asttable['FEAT_HG_LAT_DEG'][0:5]))
print(np.sin(asttable['FEAT_HG_LAT_DEG'][0:5].quantity))
# And it can also be converted to other units
print(asttable[0:5]['FEAT_AREA_DEG2'].quantity.to('arcmin2'))