1
import numpy as np
from pint import UnitRegistry 
unit = UnitRegistry()
Q_ = unit.Quantity
a = 1.0*unit.meter
b = 2.0*unit.meter
# some calculations that change a and b 
x=np.array([a.magnitude,b.magnitude])*Q_(1.0,a.units)

将从变量 a 和 b 中创建一个 numpy 数组,这些变量是品脱数量。这有点粗略,因为不能保证 a 和 b 具有相同的单位。有更清洁的方法吗?我需要写一个函数吗?

4

2 回答 2

1

在从中创建 numpy 数组之前,您应该转换为基本单位to_base_units(),无需为此编写函数,简单的列表推导就可以很好地完成。

如果您正在对数值进行大量计算,x您可能希望将其保存在参考单位中并将其用作原始数组(没有附加单位),并将单位转换限制为程序的输入/输出阶段。

import numpy as np
from pint import UnitRegistry

unit = UnitRegistry()
Q_ = unit.Quantity

a = 1.0 * unit.meter
b = 2.0 * unit.meter
c = 39.37 * unit.inch

# A list with values in different units (meters and inches)
measures = [a, b, c]

# We use a comprehension list to get the magnitudes in a base unit
x = np.array([measure.to_base_units().magnitude for measure in measures])

print x * Q_(1.0, unit.meter)

>> [ 1.        2.        0.999998] meter
于 2015-07-08T02:15:49.820 回答
1

另一种选择,允许其元素具有不同单位的数组,可能以一些效率和乐趣为代价,是给数组dtype='object'

import numpy as np
from pint import UnitRegistry 
unit = UnitRegistry()
a = 1.0*unit.meter
b = 2.0*unit.meter
# some calculations that change a and b 
x=np.array([a, b], dtype='object')
于 2019-03-22T13:40:31.300 回答