QuentinD
QuentinD

Reputation: 57

Python: Converting Astropy Table into an Array (Using Numpy?) for Plotting (on matplotlib)

I have an Astropy Table as such:

         a           b    c 
------------------- ---- ---
-0.6096212422044334  2.0 3.0
-1.2192424844088667 10.0 3.0
   -5.4865911798399  9.0 3.0

I want to turn this table back into an array for plotting purposes. This is what I tried:

d=Table(t)
x=np.array(d)
print(x)

This is what I get back (which I believe is a tuple):

[(-0.60962124,  2., 3.) (-1.21924248, 10., 3.) (-5.48659118,  9., 3.)]

When I ask for 'np.shape(x)' I get (3,) which is why I believe it is a tuple. I need the shape to be (3,3) so I can call out individual elements and plot this information.

Thank you, Q

Upvotes: 3

Views: 1053

Answers (1)

Iguananaut
Iguananaut

Reputation: 23306

This is a numpy structured array in which the "elements" of the array are not single float values, but rather triplets (in this case) of floats. It does this in part because in the general case that all columns are not the same data type, the original format of the data is still preserved (3 columns and 3 (possibly) heterogeneous rows). This is why the shape is (3,).

In this case you can safely convert to a (3, 3) homogenous array because all the columns have a floating point data type. There are a few different ways to do this but one of the easiest and safest is the structured_to_unstructured utility function.

Update: Now that at I'm at my computer, here's a concrete example based on yours:

>>> f = io.BytesIO(b"""\ 
...          a           b    c  
... ------------------- ---- --- 
... -0.6096212422044334  2.0 3.0 
... -1.2192424844088667 10.0 3.0 
...    -5.4865911798399  9.0 3.0 
... """)                                                                                       
>>> t = Table.read(f, format='ascii.fixed_width_two_line')                                     
>>> t                                                                                          
<Table length=3>
         a             b       c   
      float64       float64 float64
------------------- ------- -------
-0.6096212422044334     2.0     3.0
-1.2192424844088667    10.0     3.0
   -5.4865911798399     9.0     3.0
>>> t.as_array()                                                                               
array([(-0.60962124,  2., 3.), (-1.21924248, 10., 3.),
       (-5.48659118,  9., 3.)],
      dtype=[('a', '<f8'), ('b', '<f8'), ('c', '<f8')])
>>> a = np.lib.recfunctions.structured_to_unstructured(t.as_array())                           
>>> a                                                                                          
array([[-0.60962124,  2.        ,  3.        ],
       [-1.21924248, 10.        ,  3.        ],
       [-5.48659118,  9.        ,  3.        ]])
>>> a.shape                                                                                    
(3, 3)

Upvotes: 2

Related Questions