Access to a floating point from astrology Object distance

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

Here's the MWE:

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

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

This leads to a list of objects <class 'astropy.coordinates.distances.Distance'>:

[<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 floats (not objects), and I don't know how to get them. Since this MWE is part of a larger code, I cannot just do it d.append(_). I need to access floats from objects generated by a class Distance.

Add

I tried converting the list to a numpy array using

np.asarray(d)

but I get:

ValueError: setting an array element with a sequence.
+4
source share
3 answers

You need an attribute of valueobjects Distance.

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

... _ . , , - .

:

>>> [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]
+4

, Distance . , Distance .

>>> dists = Distance(np.arange(10), unit=u.kpc)  # Note the use of a Numpy array
>>> dists
<Distance [ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.] kpc>

Numpy . ,

>>> dists.value
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

Numpy ndarray kpc. Distance. !

+3

d = []
for _ in range(10):
    x = Distance(_, unit=u.kpc)
    d.append(x.kpc)  # x.Mpc , x.lightyear, etc. 

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

Source: https://habr.com/ru/post/1617457/


All Articles