Skip to content

Commit 8e32c95

Browse files
committed
fix safe_cast_to_index
1 parent 74e5ff6 commit 8e32c95

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ Bug fixes
6363
By `Martin Pletcher <https://github.com/pletchm>`_.
6464
- Removed usages of `pytest.config`, which is deprecated (:issue:`2988`:)
6565
By `Maximilian Roos <https://github.com/max-sixty>`_.
66+
- Fixed a bug in `utils.safe_cast_to_index` and performance issues when
67+
`cftime` is installed (:issue:`3000`:)
68+
By `0x0L <https://github.com/0x0L>`_.
6669

6770
.. _whats-new.0.12.1:
6871

xarray/core/utils.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,11 @@ def wrapper(*args, **kwargs):
6262
def _maybe_cast_to_cftimeindex(index: pd.Index) -> pd.Index:
6363
from ..coding.cftimeindex import CFTimeIndex
6464

65-
if index.dtype == 'O':
65+
if len(index) > 0 and index.dtype == 'O':
6666
try:
67+
import cftime
68+
if not isinstance(index[0], cftime.datetime):
69+
return index
6770
return CFTimeIndex(index)
6871
except (ImportError, TypeError):
6972
return index

xarray/tests/test_dataarray.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1760,6 +1760,11 @@ def test_stack_unstack(self):
17601760
orig = DataArray([[0, 1], [2, 3]], dims=['x', 'y'], attrs={'foo': 2})
17611761
assert_identical(orig, orig.unstack())
17621762

1763+
# test GH3000
1764+
a = orig[:0].stack(dim=('x', 'y')).dim.to_index()
1765+
b = pd.MultiIndex(levels=[[], [0, 1]], codes=[[], []], names=['x', 'y'])
1766+
assert a.equals(b)
1767+
17631768
actual = orig.stack(z=['x', 'y']).unstack('z').drop(['x', 'y'])
17641769
assert_identical(orig, actual)
17651770

0 commit comments

Comments
 (0)