如何从品脱数量列表中创建一个numpy数组

问题描述 投票:0回答:2
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制作一个ninty数组,它们是Pint数量。它有些粗糙,因为不能保证a和b具有相同的单位。有更清洁的方法吗?我需要写一个函数吗?

python arrays numpy
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

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')
© www.soinside.com 2019 - 2024. All rights reserved.