k.dav
k.dav

Reputation: 59

Using an array of indicies to build an Astropy table

I have two catalogs I want to build into an Astropy table and I can't seem to make it work. Both the arrays are different length and I have a third array which contains indices I need to use to build the table. The two catalogs look as follows:

c1['x'] = [11.7, 13.8, 19.2, 15.0]
c2['x'] = [12.0, 13.6, 14.5]
idx = [0, 2]

I need to create a table that only includes the first and third entries in the two catalogs. I have tried:

from astropy.table import Table
t = Table([idx, c1, cat2], names=('idx', 'x', 'x'))   
t

This gives me an error: "Inconsistent data column lengths: {4, 3}" I feel I may be going about this a strange way.

Upvotes: 0

Views: 183

Answers (1)

Christoph
Christoph

Reputation: 2940

Use Numpy arrays instead of Python lists to represent your data, and apply the row selection index idx before creating the Table.

>>> import numpy as np
>>> from astropy.table import Table
>>> c1x = np.array([11.7, 13.8, 19.2, 15.0])
>>> c2x = np.array([12.0, 13.6, 14.5])
>>> idx = np.array([0, 2])
>>> c1x[idx]
array([11.7, 19.2])
>>> c2x[idx]
array([12. , 14.5])
>>> table = Table()
>>> table['c1x'] = c1x[idx]
>>> table['c2x'] = c2x[idx]
>>> table
<Table length=2>
  c1x     c2x  
float64 float64
------- -------
   11.7    12.0
   19.2    14.5

Astropy Table internally stores data as Numpy arrays, so if you already have two tables c1 and c2 you could do this:

>>> c1 = Table()
>>> c1['x'] = [11.7, 13.8, 19.2, 15.0]
>>> c2 = Table()
>>> c2['x'] = [12.0, 13.6, 14.5]
>>> idx = [0, 2]
>>> t = Table()
>>> t['c1x'] = c1['x'][idx]
>>> t['c2x'] = c2['x'][idx]
>>> t
<Table length=2>
  c1x     c2x  
float64 float64
------- -------
   11.7    12.0
   19.2    14.5

There are many different ways to create tables, to select rows and columns from them, or to combine data from two tables into a new table. E.g. in your case you might want to apply idx to select the relevant rows in each table c1 and c2, and then join the two tables (that now have the same number of rows). See the Astropy Table docs.

Upvotes: 1

Related Questions