xarray.DataArray.astropy.to¶
- DataArray.astropy.to(units=None, equivalencies=None, **unit_kwargs)¶
convert the quantities in a DataArray
- Parameters:
units (unit-like or mapping of hashable to unit-like, optional) – The units to convert to. If a unit name or
astropy.units.Unitobject, convert the DataArray’s data. If a dict-like, it has to map a variable name to a unit name orastropy.units.Unitobject.equivalencies (
list) – A list of equivalence pairs to try if the units are not directly convertible. See Equivalencies. This list is in addition to possible global defaults set by, e.g.,astropy.units.set_enabled_equivalencies(). Use None to turn off all equivalencies.**unit_kwargs – The kwargs form of
units. Can only be used for variable names that are strings and valid python identifiers.
- Returns:
object – A new object with converted units.
- Return type:
Examples
>>> da = xr.DataArray( ... data=np.linspace(0, 1, 5) * u.m, ... coords={"u": ("x", np.arange(5) * u.s)}, ... dims="x", ... name="arr", ... ) >>> da <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [0. , 0.25, 0.5 , 0.75, 1. ] m> Coordinates: u (x) float64 40B [s] 0.0 1.0 2.0 3.0 4.0 Dimensions without coordinates: x
Convert the data
>>> da.astropy.to("mm") <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [ 0., 250., 500., 750., 1000.] mm> Coordinates: u (x) float64 40B [s] 0.0 1.0 2.0 3.0 4.0 Dimensions without coordinates: x >>> da.astropy.to(u.mm) <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [ 0., 250., 500., 750., 1000.] mm> Coordinates: u (x) float64 40B [s] 0.0 1.0 2.0 3.0 4.0 Dimensions without coordinates: x >>> da.astropy.to({da.name: "mm"}) <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [ 0., 250., 500., 750., 1000.] mm> Coordinates: u (x) float64 40B [s] 0.0 1.0 2.0 3.0 4.0 Dimensions without coordinates: x
Convert coordinates
>>> da.astropy.to({"u": u.ms}) <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [0. , 0.25, 0.5 , 0.75, 1. ] m> Coordinates: u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03 Dimensions without coordinates: x >>> da.astropy.to(u="ms") <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [0. , 0.25, 0.5 , 0.75, 1. ] m> Coordinates: u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03 Dimensions without coordinates: x
Convert both simultaneously
>>> da.astropy.to("mm", u="ms") <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [ 0., 250., 500., 750., 1000.] mm> Coordinates: u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03 Dimensions without coordinates: x >>> da.astropy.to({"arr": u.mm, "u": u.ms}) <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [ 0., 250., 500., 750., 1000.] mm> Coordinates: u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03 Dimensions without coordinates: x >>> da.astropy.to(arr="mm", u="ms") <xarray.DataArray 'arr' (x: 5)> Size: 40B <Quantity [ 0., 250., 500., 750., 1000.] mm> Coordinates: u (x) float64 40B [ms] 0.0 1e+03 2e+03 3e+03 4e+03 Dimensions without coordinates: x