Pint-Xarray
pint-xarray provides an interface between Pint (physical units library) and xarray (labeled multi-dimensional arrays). It enables attaching units to `xarray.DataArray` and `xarray.Dataset` objects, performing unit-aware computations, and ensuring dimensional consistency, making scientific data processing more robust. It is currently at version 0.6.1 and sees active development with releases typically tied to feature additions and bug fixes.
Common errors
-
AttributeError: 'DataArray' object has no attribute 'pint'
cause The `pint_xarray` accessor was not registered with xarray. This happens if `import pint_xarray` is omitted or placed after the `xarray.DataArray` creation in certain environments.fixAdd `import pint_xarray` at the beginning of your script or before you attempt to use the `.pint` accessor. The import statement itself registers the accessor. -
pint.errors.DimensionalityError: Cannot convert from 'meter' to 'second'
cause You attempted an operation (e.g., addition, conversion) between two quantities that have fundamentally incompatible dimensions (e.g., length and time). Pint strictly enforces dimensional correctness.fixReview the units of the involved DataArrays or Quantities. Ensure they are dimensionally compatible before performing the operation. If a conversion is intended, ensure the target unit is dimensionally consistent (e.g., `da.pint.to('kilometer')` for a meter-quantified array).
Warnings
- breaking Starting from version 0.5.0, `pint-xarray` changed its internal unit storage mechanism. Units are now stored as `pint.Quantity` objects within a custom `pint_units` backend, rather than as strings in `xarray.DataArray.attrs`. This enhances unit propagation and ensures better integration with Pint's features.
- deprecated The `convert_units` function (e.g., `pint_xarray.convert_units(da, 'meter')`) has been removed in favor of the `.pint.to()` accessor method.
- gotcha When performing operations with quantified xarray objects, Pint's strict unit checking will enforce dimensional consistency. Attempting operations on quantities with incompatible dimensions will raise a `DimensionalityError`.
- gotcha Using `pint-xarray` for computations will ensure unit propagation for many operations, but it does not magically resolve all unit inconsistencies in every scenario. For example, some non-unit-aware xarray methods might still drop unit metadata if not handled correctly.
Install
-
pip install pint-xarray
Imports
- pint_xarray
import pint_xarray
- DataArray.pint
da.attrs['units'] = 'meter'
da.pint.quantify(...)
- Dataset.pint
ds['var'].attrs['units'] = 'meter'
ds.pint.quantify(...)
Quickstart
import xarray as xr
import pint_xarray # noqa: F401 (registers accessor)
import pint
import numpy as np
# Create a Pint UnitRegistry
ureg = pint.UnitRegistry()
# Create an xarray DataArray with units using the .pint accessor
da = xr.DataArray(
np.array([10.0, 20.0, 30.0]),
coords={"x": [0, 1, 2]},
dims=("x",),
).pint.quantify(unit=ureg.meter)
print("Original DataArray:")
print(da)
# Perform a unit-aware operation: convert units
da_km = da.pint.to("kilometer")
print("\nConverted to kilometers:")
print(da_km)
# Example with a Dataset and multiple variables
ds = xr.Dataset(
{
"temperature": ("time", [25.0, 26.0]),
"pressure": ("time", [1013.25, 1012.00])
},
coords={"time": [0, 1]}
).pint.quantify({"temperature": ureg.degC, "pressure": ureg.hPa})
print("\nOriginal Dataset variable 'temperature':")
print(ds["temperature"])
# Convert a Dataset variable's units
temp_kelvin = ds["temperature"].pint.to("kelvin")
print("\nTemperature in Kelvin:")
print(temp_kelvin)