Python 如何使用astropy单位从文字创建numpy数组?

Python 如何使用astropy单位从文字创建numpy数组?,python,astropy,Python,Astropy,我的方法接收的标量值“伪装”为天文量。我想用它们制作一个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) 这不起作

我的方法接收的标量值“伪装”为天文量。我想用它们制作一个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:只有无量纲标量可以转换为Python标量

我改变了方法,所以它首先将每个人转换成相同的单位,然后我应用这个单位

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

对我来说,这似乎是陈词滥调,有没有更优雅的方式来写这篇文章?我在astropy的单位系统中观察到了什么?

我不确定除了一个只有一个单位的同质NumPy阵列之外,是否还可能有任何其他的单位具有
astropy.units
。您可能希望使用Pandas数据帧,并为每一列使用不同的数组和自己的单元。 如果您可以使用不同的库,请查看。它只会将您的单位转换为普通单位:

导入品脱
将numpy作为np导入
ureg=pint.UnitRegistry()
a=[3,4]*ureg.meter+[4,3]*ureg.cm
# 
np.总和(a)
# 

我想品脱也存在同样的问题:
a=np.array([3*ureg.meter,4*ureg.meter])
?没错。一种解决方案是使用
object
dtype:
a=np.array([3*ureg.meter,4*ureg.meter],dtype='object')
。见: