Skip to content

Commit f83ad9e

Browse files
authored
Raise NotImplementedError when attempting to save a MultiIndex to disk. (#1713)
xref GH1547
1 parent 9cffe1f commit f83ad9e

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/whats-new.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ Bug fixes
6262
DataArray constructor (:issue:`1709`).
6363
By `Stephan Hoyer <https://github.com/shoyer>`_.
6464

65+
- Raise ``NotImplementedError`` when attempting to save a MultiIndex to a
66+
netCDF file (:issue:`1547`).
67+
By `Stephan Hoyer <https://github.com/shoyer>`_.
68+
6569
Testing
6670
~~~~~~~
6771

xarray/conventions.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
from .core import duck_array_ops, indexing, ops, utils
1919
from .core.formatting import format_timestamp, first_n_items, last_item
20-
from .core.variable import as_variable, Variable
20+
from .core.variable import as_variable, IndexVariable, Variable
2121
from .core.pycompat import iteritems, OrderedDict, PY3, basestring
2222

2323

@@ -832,6 +832,15 @@ def _infer_dtype(array, name=None):
832832
def ensure_dtype_not_object(var, name=None):
833833
# TODO: move this from conventions to backends? (it's not CF related)
834834
if var.dtype.kind == 'O':
835+
if (isinstance(var, IndexVariable) and
836+
isinstance(var.to_index(), pd.MultiIndex)):
837+
raise NotImplementedError(
838+
'variable {!r} is a MultiIndex, which cannot yet be '
839+
'serialized to netCDF files '
840+
'(https://github.com/pydata/xarray/issues/1077). Use '
841+
'reset_index() to convert MultiIndex levels into coordinate '
842+
'variables instead.'.format(name))
843+
835844
dims, data, attrs, encoding = _var_as_tuple(var)
836845
missing = pd.isnull(data)
837846
if missing.any():

xarray/tests/test_backends.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,13 @@ def test_append_overwrite_values(self):
719719
def test_vectorized_indexing(self):
720720
self._test_vectorized_indexing(vindex_support=False)
721721

722+
def test_multiindex_not_implemented(self):
723+
ds = (Dataset(coords={'y': ('x', [1, 2]), 'z': ('x', ['a', 'b'])})
724+
.set_index(x=['y', 'z']))
725+
with raises_regex(NotImplementedError, 'MultiIndex'):
726+
with self.roundtrip(ds):
727+
pass
728+
722729

723730
_counter = itertools.count()
724731

0 commit comments

Comments
 (0)