pythonarraysnumpypint

how do I make a numpy array from a list of pint quantities


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)

will make a numpy array from variables a and b which are Pint quantities. It is somewhat crude as there is no guarantee that a and b have the same units. Is there a cleaner way to do it? Do I need to write a function?


Solution

  • This can now be done with the from_list method of pint.Quantity:

    import pint
    unit = pint.UnitRegistry()
    a = 1.0*unit.meter
    b = 2.0*unit.meter
    print(pint.Quantity.from_list([a, b]))
    >> [1.0 2.0] meter