Skip to content

Commit 08a57ba

Browse files
mgunyhodcherian
andcommitted
Raise exception if a variable is also a coordinate in to_dataset
Co-authored-by: Deepak Cherian <[email protected]>
1 parent 303e88f commit 08a57ba

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

xarray/core/dataarray.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -579,9 +579,22 @@ def subset(dim, label):
579579
array.attrs = {}
580580
return as_variable(array)
581581

582-
variables = {label: subset(dim, label) for label in self.get_index(dim)}
583-
variables.update({k: v for k, v in self._coords.items() if k != dim})
582+
variables_from_split = {
583+
label: subset(dim, label) for label in self.get_index(dim)
584+
}
584585
coord_names = set(self._coords) - {dim}
586+
587+
ambiguous_vars = set(variables_from_split) & coord_names
588+
if ambiguous_vars:
589+
rename_msg_fmt = ", ".join([f"{v}=..." for v in sorted(ambiguous_vars)])
590+
raise ValueError(
591+
f"Splitting along the dimension {dim!r} would produce the variables "
592+
f"{tuple(sorted(ambiguous_vars))} which are also existing coordinate "
593+
f"variables. Use DataArray.rename({rename_msg_fmt}) or "
594+
f"DataArray.assign_coords({dim}=...) to resolve this ambiguity."
595+
)
596+
597+
variables = variables_from_split | {c: self._coords[c] for c in coord_names}
585598
indexes = filter_indexes_from_coords(self._indexes, coord_names)
586599
dataset = Dataset._construct_direct(
587600
variables, coord_names, indexes=indexes, attrs=self.attrs

0 commit comments

Comments
 (0)