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)

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?

Morwenn
  • 21,684
  • 12
  • 93
  • 152
pheon
  • 2,867
  • 3
  • 26
  • 33

3 Answers3

2

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
1

You should convert to a base unit with to_base_units() before creating a numpy array from it, no need to write a function for this, a simple list comprehension will do it nicely.

If you're doing numerically heavy calculations on x you probably will want to keep it in a reference unit and use it as a raw array (without attached unit), and limit the unit conversions to the input/output phase of the program.

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
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • 1
    That's nice, if slightly longer. I like to keep the units around, because an error in units when adding two variables, indicates an error in the calculation. – pheon Jul 08 '15 at 12:51
1

Another option, which allows for arrays whose elements have different units, probably at the cost of some efficiency and fun is to give the array 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')
Oliver Evans
  • 1,405
  • 14
  • 17