如何使用天文单位从文字创建numpy数组



我的方法接收标量值"伪装的";作为天体数量。我想用它们制作一个numpy数组,它将携带相同的(基本(单元。

以下是我最初所做的:

from astropy.units import km, m
from astropy.units.quantity import Quantity
import numpy as np
def method(a: Quantity, b: Quantity):
c = np.array((a, b))
method(3 * km, 2000 * m)

这不起作用:TypeError: only dimensionless scalar quantities can be converted to Python scalars

我改变了这个方法,它首先将每个人转换为同一个单元,然后我应用这个单元。

def method(a: Quantity, b: Quantity):
c = np.array((a.to('km').value, b.to('km').value)) * km

对我来说,这似乎是板上钉钉的事,有没有更优雅的写作方式?我在天体物理学的单位系统中监督过的东西?

除了一个只有astropy.units单元的同构NumPy数组之外,我不确定是否可能有其他东西。您可能希望使用Pandas DataFrame,并为每列提供一个不同的数组,并有自己的单元。如果您可以使用其他库,请查看https://pint.readthedocs.io.它只会把你的单位转换成一个普通的单位:

import pint
import numpy as np
ureg = pint.UnitRegistry()
a = [3, 4] * ureg.meter + [4, 3] * ureg.cm
# <Quantity([ 3.04  4.03], 'meter')>
np.sum(a)
# <Quantity(7.07, 'meter')>

最新更新