Skip to content

Commit fe10ca1

Browse files
authored
avoid destroying MultiIndex objects in dequantify (#168)
* add the test from the issue * don't try to strip units if the variable does not contain a quantity * changelog * issue numbers
1 parent 2942549 commit fe10ca1

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

docs/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ What's new
88
By `Justus Magin <https://github.com/keewis>`_.
99
- add support for python 3.10 (:pull:`155`)
1010
By `Justus Magin <https://github.com/keewis>`_.
11+
- preserve :py:class:`pandas.MultiIndex` objects (:issue:`164`, :pull:`168`).
12+
By `Justus Magin <https://github.com/keewis>`_.
1113

1214
0.2.1 (26 Jul 2021)
1315
-------------------

pint_xarray/conversion.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,9 @@ def extract_unit_attributes(obj, attr="units"):
282282

283283

284284
def strip_units_variable(var):
285+
if not isinstance(var.data, pint.Quantity):
286+
return var
287+
285288
data = array_strip_units(var.data)
286289
return var.copy(data=data)
287290

pint_xarray/tests/test_accessors.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import numpy as np
2+
import pandas as pd
23
import pint
34
import pytest
45
import xarray as xr
@@ -174,6 +175,17 @@ def test_roundtrip_data(self, example_unitless_da):
174175
result = quantified.pint.dequantify()
175176
assert_equal(result, orig)
176177

178+
def test_multiindex(self):
179+
mindex = pd.MultiIndex.from_product([["a", "b"], [1, 2]], names=("lat", "lon"))
180+
181+
da = xr.DataArray(
182+
np.arange(len(mindex)), dims="multi", coords={"multi": mindex}
183+
)
184+
result = da.pint.dequantify()
185+
186+
xr.testing.assert_identical(da, result)
187+
assert isinstance(result.indexes["multi"], pd.MultiIndex)
188+
177189

178190
class TestPropertiesDataArray:
179191
def test_magnitude_getattr(self, example_quantity_da):

0 commit comments

Comments
 (0)