Astropy 数量就地转换
Astropy quantity in-place conversion
有没有办法将天文量转换为另一组单位"in-place"? to
方法总是 returns 一个副本,所以这不是很有用。类似于:
import astropy.units as u
data = [1, 2, 3]*u.g
data.convert_to('kg')
Pint
和 yt.units
都有就地转换:
from pint import UnitRegistry
u = UnitRegistry()
data = [1, 2, 3]*u.g
data.ito('kg')
和
from yt.units import g
data = [1, 2, 3]*g
data.convert_to_units('kg')
粗略浏览一下 astropy 文档和源代码表明答案是 "no" 但也许我遗漏了什么。
目前有几种方法可以做到这一点。举个例子:
>>> import astropy.units as u
>>> data = [1, 2, 3] * u.g
>>> data
<Quantity [1., 2., 3.] g>
你可以这样做:
>>> data.value * u.kg
<Quantity [1., 2., 3.] kg>
或者这样:
>>> data * u.kg / data.unit
<Quantity [1., 2., 3.] kg>
或者这样:
>>> data._unit = u.kg
>>> data
<Quantity [1., 2., 3.] kg>
None 这些方法复制 Numpy 数组,因此对于许多应用程序来说在性能方面是可行的。
我认为没有一种方法可以在不访问私有数据成员的情况下设置 data._unit
。对此进行了一些讨论(在 Column 和 Quantity 对象的上下文中)here and I think the conclusion was that a set_unit
method would be a useful addition, but it hasn't been implemented yet. So you could open an issue with that feature request here.
有没有办法将天文量转换为另一组单位"in-place"? to
方法总是 returns 一个副本,所以这不是很有用。类似于:
import astropy.units as u
data = [1, 2, 3]*u.g
data.convert_to('kg')
Pint
和 yt.units
都有就地转换:
from pint import UnitRegistry
u = UnitRegistry()
data = [1, 2, 3]*u.g
data.ito('kg')
和
from yt.units import g
data = [1, 2, 3]*g
data.convert_to_units('kg')
粗略浏览一下 astropy 文档和源代码表明答案是 "no" 但也许我遗漏了什么。
目前有几种方法可以做到这一点。举个例子:
>>> import astropy.units as u
>>> data = [1, 2, 3] * u.g
>>> data
<Quantity [1., 2., 3.] g>
你可以这样做:
>>> data.value * u.kg
<Quantity [1., 2., 3.] kg>
或者这样:
>>> data * u.kg / data.unit
<Quantity [1., 2., 3.] kg>
或者这样:
>>> data._unit = u.kg
>>> data
<Quantity [1., 2., 3.] kg>
None 这些方法复制 Numpy 数组,因此对于许多应用程序来说在性能方面是可行的。
我认为没有一种方法可以在不访问私有数据成员的情况下设置 data._unit
。对此进行了一些讨论(在 Column 和 Quantity 对象的上下文中)here and I think the conclusion was that a set_unit
method would be a useful addition, but it hasn't been implemented yet. So you could open an issue with that feature request here.