Skip to content

Commit 341b47b

Browse files
author
Benoit Bovy
committed
check for uniqueness of multi-index level names
1 parent 53bd749 commit 341b47b

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

xarray/core/dataarray.py

+10
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ def _infer_coords_and_dims(shape, coords, dims):
6868
new_coords[dim] = default_index_coordinate(dim, size)
6969

7070
sizes = dict(zip(dims, shape))
71+
level_names = {}
7172
for k, v in new_coords.items():
7273
if any(d not in dims for d in v.dims):
7374
raise ValueError('coordinate %s has dimensions %s, but these '
@@ -80,6 +81,15 @@ def _infer_coords_and_dims(shape, coords, dims):
8081
'length %s on the data but length %s on '
8182
'coordinate %r' % (d, sizes[d], s, k))
8283

84+
if v.ndim == 1:
85+
idx_level_names = v.to_coord().level_names or []
86+
for n in idx_level_names:
87+
if n in level_names:
88+
raise ValueError('found duplicate MultiIndex level '
89+
'name %r for coordinates %r and %r'
90+
% (n, k, level_names[n]))
91+
level_names[n] = k
92+
8393
return new_coords, dims
8494

8595

xarray/core/dataset.py

+16
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ def __init__(self, data_vars=None, coords=None, attrs=None,
224224
coords = {}
225225
if data_vars is not None or coords is not None:
226226
self._set_init_vars_and_dims(data_vars, coords, compat)
227+
self._check_multiindex_level_names()
227228
if attrs is not None:
228229
self.attrs = attrs
229230
self._initialized = True
@@ -250,6 +251,21 @@ def _set_init_vars_and_dims(self, data_vars, coords, compat):
250251
self._coord_names = coord_names
251252
self._dims = dims
252253

254+
def _check_multiindex_level_names(self):
255+
"""Check for uniqueness of MultiIndex level names
256+
"""
257+
level_names = {}
258+
for c in self._coord_names:
259+
v = self._variables[c]
260+
if v.ndim == 1 and v._in_memory:
261+
idx_level_names = v.to_coord().level_names or []
262+
for n in idx_level_names:
263+
if n in level_names:
264+
raise ValueError('found duplicate MultiIndex level '
265+
'name %r for coordinates %r and %r'
266+
% (n, c, level_names[n]))
267+
level_names[n] = c
268+
253269
@classmethod
254270
def load_store(cls, store, decoder=None):
255271
"""Create a new dataset from the contents of a backends.*DataStore

0 commit comments

Comments
 (0)