xarray-contrib / pint-xarray

Interface for using pint with xarray, providing convenience accessors
https://pint-xarray.readthedocs.io/en/latest/
Apache License 2.0
103 stars 12 forks source link

da.mean() is dropping pint units #257

Closed jalder-usgs closed 2 months ago

jalder-usgs commented 3 months ago

I'm relatively new to xarray and pint, but the example isn't working as on the web page:

ds = xr.tutorial.open_dataset("air_temperature")
data = ds.air
data

quantified = data.pint.quantify()
quantified

monthly_means = quantified.pint.to("degC").sel(time="2013").groupby("time.month").mean()
monthly_means

Running this sample locally gives this warning:

python3.12/site-packages/xarray/namedarray/core.py:215): UnitStrippedWarning: The unit of the quantity is stripped when downcasting to ndarray.

Here the .mean() function is stripping the quantified pint units (unlike the example web page). The values are clearly in the degC range, so dequantify() has been called under the hood, but basic DataArray functions like mean() shouldn't be dropping the pint units.


Python     : 3.12.3 | packaged by conda-forge | (main, Apr 15 2024, 18:50:49) [Clang 16.0.6 ]
cf_xarray  : 0.9.1
pint_xarray : 0.3
xarray     : 2024.5.0
keewis commented 3 months ago

Thanks for the report. That warning occurs if pint discards the unit information implicitly, and is usually (but not always) a sign that something is going wrong.

Which version of pint do you use? pint=0.24, which was released a coupled of days ago to PyPI (not sure about conda-forge), should not have this issue (it has a bunch of other issues regarding unit formatters, though).

Otherwise try in an environment with python<3.12 (e.g. python=3.11). python=3.12 changed the way attribute lookup works (if I remember correctly), which meant that pint had to adapt.

In other words, I think this is an issue within pint.

jalder-usgs commented 3 months ago

Thanks, it was using pint=0.23.

I followed your suggestion and started with a fresh Conda environment using python=3.11 and it is good to go now.

keewis commented 2 months ago

pint=0.24.1 is out (which fixes the issues I mentioned above), so I'll close this.