Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从一个品脱数量列表中生成numpy数组_Python_Arrays_Numpy_Pint - Fatal编程技术网

Python 如何从一个品脱数量列表中生成numpy数组

Python 如何从一个品脱数量列表中生成numpy数组,python,arrays,numpy,pint,Python,Arrays,Numpy,Pint,将从变量a和b中生成一个numpy数组,这两个变量都是小数量。这有点粗糙,因为不能保证a和b有相同的单位。有没有更干净的方法?我需要写一个函数吗?在创建numpy数组之前,你应该先用转换成一个基本单位,然后再使用转换成\u base\u units(),无需为此编写函数,简单的列表理解就可以了 如果您在x上进行大量数值计算,您可能希望将其保留在参考单元中,并将其用作原始数组(无附加单元),并将单元转换限制在程序的输入/输出阶段 import numpy as np from pint impor

将从变量a和b中生成一个numpy数组,这两个变量都是小数量。这有点粗糙,因为不能保证a和b有相同的单位。有没有更干净的方法?我需要写一个函数吗?

在创建numpy数组之前,你应该先用
转换成一个基本单位,然后再使用
转换成\u base\u 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
# some calculations that change a and b 
x=np.array([a.magnitude,b.magnitude])*Q_(1.0,a.units)

另一个选项是为数组提供
dtype='object'
,该选项允许元素具有不同单位的数组,但可能会牺牲一些效率和乐趣

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

如果稍微长一点,那很好。我喜欢保留单位,因为当添加两个变量时,单位中的错误表示计算中的错误。有趣的建议,但是有没有一种方法可以先用浮点值声明数组,然后应用元素形式的数量对象转换?@user32882一个选项是
v=[3.0,4.5,5.7];x=np.array([e*unit.meter表示v中的e],dtype=object)
新项目
pint pandas
正在尝试为
pandas
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')