Skip to content

Commit 6134b61

Browse files
authored
ensure index units are attached and converted correctly (#368)
* avoid nesting `PintIndex` instances * correctly compute the index units * whats-new [skip-ci][test-upstream]
1 parent 296ee2e commit 6134b61

File tree

3 files changed

+13
-7
lines changed

3 files changed

+13
-7
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
- Don't rely on ``xarray``'s default behavior regarding ``attrs`` in :py:func:`pint_xarray.expects` (:issue:`360`, :pull:`367`)
1010
By `Justus Magin <https://github.com/keewis>`_.
11+
- Fix quantifying a existing index and adjust the index conversion tests (:pull:`368`)
12+
By `Justus Magin <https://github.com/keewis>`_.
1113

1214
0.6.0 (31 Aug 2025)
1315
-------------------

pint_xarray/conversion.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -137,10 +137,13 @@ def attach_units_index(index, index_vars, units):
137137
# skip non-quantity indexed variables
138138
return index
139139

140-
if isinstance(index, PintIndex) and index.units != units:
141-
raise ValueError(
142-
f"cannot attach units to quantified index: {index.units} != {units}"
143-
)
140+
if isinstance(index, PintIndex):
141+
if index.units != units:
142+
raise ValueError(
143+
f"cannot attach units to quantified index: {index.units} != {units}"
144+
)
145+
else:
146+
return index
144147

145148
return PintIndex(index=index, units=units)
146149

pint_xarray/tests/test_conversion.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -418,11 +418,12 @@ def test_convert_units(self, type, variant, units, error, suberrors):
418418
expected_a = convert_quantity(q_a, units.get("a", original_units.get("a")))
419419
expected_b = convert_quantity(q_b, units.get("b", original_units.get("b")))
420420
expected_u = convert_quantity(q_u, units.get("u", original_units.get("u")))
421-
expected_x = convert_quantity(q_x, units.get("x"))
421+
expected_x = convert_quantity(q_x, units.get("x", original_units.get("x")))
422422
expected_index = PandasIndex(pd.Index(strip_quantity(expected_x)), "x")
423-
if units.get("x") is not None:
423+
expected_index_units = units.get("x", original_units.get("x"))
424+
if expected_index_units is not None:
424425
expected_index = PintIndex(
425-
index=expected_index, units={"x": units.get("x")}
426+
index=expected_index, units={"x": expected_index_units}
426427
)
427428

428429
expected = Dataset(

0 commit comments

Comments
 (0)