Converting units¶
When working with Dataset or DataArray objects with
units, we frequently might want to convert the units. Suppose we have:
In [1]: ds = xr.Dataset(
...: {"a": ("x", [4, 8, 12, 16])}, coords={"u": ("x", [10, 20, 30, 40])}
...: ).astropy.quantify({"a": "m", "u": "s"})
...: ds
...:
Out[1]:
<xarray.Dataset> Size: 64B
Dimensions: (x: 4)
Coordinates:
u (x) float64 32B [s] 10.0 20.0 30.0 40.0
Dimensions without coordinates: x
Data variables:
a (x) float64 32B [m] 4.0 8.0 12.0 16.0
In [2]: da = ds.a
...: da
...:
Out[2]:
<xarray.DataArray 'a' (x: 4)> Size: 32B
<Quantity [ 4., 8., 12., 16.] m>
Coordinates:
u (x) float64 32B [s] 10.0 20.0 30.0 40.0
Dimensions without coordinates: x
To convert the data to different units, we can use the
Dataset.astropy.to() and DataArray.astropy.to() methods:
In [3]: ds.astropy.to(a="cm", u="ks")
Out[3]:
<xarray.Dataset> Size: 64B
Dimensions: (x: 4)
Coordinates:
u (x) float64 32B [ks] 0.01 0.02 0.03 0.04
Dimensions without coordinates: x
Data variables:
a (x) float64 32B [cm] 400.0 800.0 1.2e+03 1.6e+03
In [4]: da.astropy.to({da.name: "km", "u": "ms"})
Out[4]:
<xarray.DataArray 'a' (x: 4)> Size: 32B
<Quantity [0.004, 0.008, 0.012, 0.016] km>
Coordinates:
u (x) float64 32B [ms] 1e+04 2e+04 3e+04 4e+04
Dimensions without coordinates: x