Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access float value from astropy Distance object

Tags:

python

astropy

I need to access the float value from the Distance astropy class.

Here'a a MWE:

from astropy.coordinates import Distance
from astropy import units as u

d = []
for _ in range(10):
    d.append(Distance(_, unit=u.kpc))

This results in a list of <class 'astropy.coordinates.distances.Distance'> objects:

[<Distance 0.0 kpc>, <Distance 1.0 kpc>, <Distance 2.0 kpc>, <Distance 3.0 kpc>, <Distance 4.0 kpc>, <Distance 5.0 kpc>, <Distance 6.0 kpc>, <Distance 7.0 kpc>, <Distance 8.0 kpc>, <Distance 9.0 kpc>]

I need to store the floats (not the objects) and I don't know how to access them. Since this MWE is part of a larger code, I can't just do d.append(_). I need to access the floats from the objects generated by the Distance class.

Add:

I tried converting the list to a numpy array with:

np.asarray(d)

but I get:

ValueError: setting an array element with a sequence.
like image 966
Gabriel Avatar asked Feb 09 '23 11:02

Gabriel


1 Answers

You want the value attribute of the Distance objects.

d = []
for _ in range(10):
    d.append(Distance(_, unit=u.kpc).value)

...but then you might as well just use your variable _ without instantiating those objects in the first place. Or maybe I'm misunderstood something.

Another way to put it:

>>> [i.value for i in d]
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
like image 174
Matt Hall Avatar answered Feb 12 '23 12:02

Matt Hall