Skip to content

Commit 300ec8e

Browse files
committed
first draft of the pint-xarray index demo
1 parent e0565bf commit 300ec8e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

docs/agnostic/pint.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,61 @@ align: center
2525
Learn more at the [pint-xarray](https://pint-xarray.readthedocs.io/en/latest/) documentation page.
2626
```
2727
````
28+
29+
## Highlights
30+
31+
`pint-xarray` provides an index that wraps other indexes and attaches units to the indexed coordinates. This allows operations like `integrate` or `sel` to take the units into account.
32+
33+
## Example
34+
35+
First we open the dataset and perform some preprocessing:
36+
37+
```{python}
38+
import numpy as np
39+
import xarray as xr
40+
41+
xr.set_options(
42+
display_expand_indexes=True, display_expand_attrs=False, display_expand_data=False
43+
)
44+
45+
ds = (
46+
xr.tutorial.open_dataset("eraint_uvz")
47+
.load()
48+
.assign_coords(months=lambda ds: ds["months"].assign_attrs({"units": "months"}))
49+
.assign(windspeed=lambda ds: np.hypot(ds["u"], ds["v"]))
50+
)
51+
ds
52+
```
53+
54+
### Quantifying
55+
56+
Now we can quantify to convert arrays with a `"units"` attribute to quantity arrays:
57+
58+
```{python}
59+
import cf_xarray.units
60+
import pint_xarray
61+
62+
quantified = ds.pint.quantify()
63+
quantified
64+
```
65+
66+
Note how all variables are associated with a {py:class}`pint.Quantity` array, and how all coordinate variables are associated with a {py:class}`pint_xarray.PintIndex` wrapping a `PandasIndex`.
67+
68+
### Selection
69+
70+
Selecting with quantities will do the right thing, converting to the index' units:
71+
72+
```{python}
73+
quantified.sel(
74+
latitude=slice(ureg.Quantity(4800, "arcmin"), ureg.Quantity(600, "arcmin")),
75+
longitude=slice(ureg.Quantity(-10, "degree"), ureg.Quantity(np.pi, "radians")),
76+
)
77+
```
78+
79+
or raising on incompatible units:
80+
81+
```{python}
82+
quantified.sel(
83+
months=ureg.Quantity(10, "m")
84+
)
85+
```

0 commit comments

Comments
 (0)