How to Convert xarray Units from Celsius to Kelvin¶
This how-to shows how to convert the values of an xarray.DataArray (or xarray.Dataset) from degrees Celsius to Kelvin using earthkit.utils.units.convert_units.
[1]:
import xarray as xr
from earthkit.utils.units import convert_units
Convert a DataArray¶
Create a DataArray with a units attribute set to "degC". The converter reads source units from the attribute automatically, so only target_units needs to be specified.
[2]:
temperature = xr.DataArray(
[0.0, 20.0, 100.0],
dims="x",
name="temperature",
attrs={"units": "degC"},
)
temperature_K = convert_units(temperature, target_units="K")
print(temperature_K.values) # [273.15 293.15 373.15]
print(temperature_K.attrs["units"]) # K
[273.15 293.15 373.15]
K
Override Source Units Explicitly¶
If the units attribute is absent or incorrect, pass source_units to override it:
[3]:
# DataArray without a units attribute
temperature_no_attr = xr.DataArray([0.0, 20.0, 100.0], dims="x")
temperature_K = convert_units(
temperature_no_attr,
target_units="K",
source_units="degC",
)
print(temperature_K.values) # [273.15 293.15 373.15]
[273.15 293.15 373.15]
Convert a Dataset¶
Use a target_units dict to specify the target unit per variable. Only the named variable is converted; others are left unchanged.
[4]:
ds = xr.Dataset({
"temperature": xr.DataArray([0.0, 20.0], dims="x", attrs={"units": "degC"}),
"pressure": xr.DataArray([1013.25, 1000.0], dims="x", attrs={"units": "hPa"}),
})
result = convert_units(ds, target_units={"temperature": "K"})
print(result["temperature"].values) # [273.15 293.15]
print(result["temperature"].attrs["units"]) # K
print(result["pressure"].values) # [1013.25 1000. ] — unchanged
[273.15 293.15]
K
[1013.25 1000. ]