Skip to content

Commit 0a3bb18

Browse files
gwgundersenmax-sixty
authored andcommitted
Manually reverting because something added a comment after a ton of arguments. (#3228)
1 parent d578bfe commit 0a3bb18

File tree

5 files changed

+77
-3
lines changed

5 files changed

+77
-3
lines changed

doc/whats-new.rst

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,15 @@ Enhancements
6565
``append_dim`` is set, as it will automatically be set to ``'a'`` internally.
6666
By `David Brochart <https://github.com/davidbrochart>`_.
6767

68-
- :py:meth:`~xarray.Dataset.drop` now supports keyword arguments; dropping index labels by specifying both ``dim`` and ``labels`` is deprecated (:issue:`2910`).
68+
- :py:meth:`~xarray.Dataset.drop` now supports keyword arguments; dropping index
69+
labels by specifying both ``dim`` and ``labels`` is deprecated (:issue:`2910`).
6970
By `Gregory Gundersen <https://github.com/gwgundersen/>`_.
7071

72+
- Added examples of :py:meth:`Dataset.set_index` and
73+
:py:meth:`DataArray.set_index`, as well are more specific error messages
74+
when the user passes invalid arguments (:issue:`3176`).
75+
By `Gregory Gundersen <https://github.com/gwgundersen>`_.
76+
7177
Bug fixes
7278
~~~~~~~~~
7379
- Fix regression introduced in v0.12.2 where ``copy(deep=True)`` would convert

xarray/core/dataarray.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1524,6 +1524,30 @@ def set_index(
15241524
Another DataArray, with this data but replaced coordinates.
15251525
Return None if inplace=True.
15261526
1527+
Example
1528+
-------
1529+
>>> arr = xr.DataArray(data=np.ones((2, 3)),
1530+
... dims=['x', 'y'],
1531+
... coords={'x':
1532+
... range(2), 'y':
1533+
... range(3), 'a': ('x', [3, 4])
1534+
... })
1535+
>>> arr
1536+
<xarray.DataArray (x: 2, y: 3)>
1537+
array([[1., 1., 1.],
1538+
[1., 1., 1.]])
1539+
Coordinates:
1540+
* x (x) int64 0 1
1541+
* y (y) int64 0 1 2
1542+
a (x) int64 3 4
1543+
>>> arr.set_index(x='a')
1544+
<xarray.DataArray (x: 2, y: 3)>
1545+
array([[1., 1., 1.],
1546+
[1., 1., 1.]])
1547+
Coordinates:
1548+
* x (x) int64 3 4
1549+
* y (y) int64 0 1 2
1550+
15271551
See Also
15281552
--------
15291553
DataArray.reset_index

xarray/core/dataset.py

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ def merge_indexes(
198198
"""
199199
vars_to_replace = {} # Dict[Any, Variable]
200200
vars_to_remove = [] # type: list
201+
error_msg = "{} is not the name of an existing variable."
201202

202203
for dim, var_names in indexes.items():
203204
if isinstance(var_names, str) or not isinstance(var_names, Sequence):
@@ -207,7 +208,10 @@ def merge_indexes(
207208
current_index_variable = variables.get(dim)
208209

209210
for n in var_names:
210-
var = variables[n]
211+
try:
212+
var = variables[n]
213+
except KeyError:
214+
raise ValueError(error_msg.format(n))
211215
if (
212216
current_index_variable is not None
213217
and var.dims != current_index_variable.dims
@@ -239,8 +243,11 @@ def merge_indexes(
239243

240244
else:
241245
for n in var_names:
246+
try:
247+
var = variables[n]
248+
except KeyError:
249+
raise ValueError(error_msg.format(n))
242250
names.append(n)
243-
var = variables[n]
244251
cat = pd.Categorical(var.values, ordered=True)
245252
codes.append(cat.codes)
246253
levels.append(cat.categories)
@@ -2952,6 +2959,33 @@ def set_index(
29522959
obj : Dataset
29532960
Another dataset, with this dataset's data but replaced coordinates.
29542961
2962+
Examples
2963+
--------
2964+
>>> arr = xr.DataArray(data=np.ones((2, 3)),
2965+
... dims=['x', 'y'],
2966+
... coords={'x':
2967+
... range(2), 'y':
2968+
... range(3), 'a': ('x', [3, 4])
2969+
... })
2970+
>>> ds = xr.Dataset({'v': arr})
2971+
>>> ds
2972+
<xarray.Dataset>
2973+
Dimensions: (x: 2, y: 3)
2974+
Coordinates:
2975+
* x (x) int64 0 1
2976+
* y (y) int64 0 1 2
2977+
a (x) int64 3 4
2978+
Data variables:
2979+
v (x, y) float64 1.0 1.0 1.0 1.0 1.0 1.0
2980+
>>> ds.set_index(x='a')
2981+
<xarray.Dataset>
2982+
Dimensions: (x: 2, y: 3)
2983+
Coordinates:
2984+
* x (x) int64 3 4
2985+
* y (y) int64 0 1 2
2986+
Data variables:
2987+
v (x, y) float64 1.0 1.0 1.0 1.0 1.0 1.0
2988+
29552989
See Also
29562990
--------
29572991
Dataset.reset_index

xarray/tests/test_dataarray.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1716,6 +1716,11 @@ def test_set_index(self):
17161716
with raises_regex(ValueError, "dimension mismatch"):
17171717
array2d.set_index(x="level")
17181718

1719+
# Issue 3176: Ensure clear error message on key error.
1720+
with pytest.raises(ValueError) as excinfo:
1721+
obj.set_index(x="level_4")
1722+
assert str(excinfo.value) == "level_4 is not the name of an existing variable."
1723+
17191724
def test_reset_index(self):
17201725
indexes = [self.mindex.get_level_values(n) for n in self.mindex.names]
17211726
coords = {idx.name: ("x", idx) for idx in indexes}

xarray/tests/test_dataset.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2712,6 +2712,11 @@ def test_set_index(self):
27122712
expected = Dataset(coords={"x": [0, 1, 2]})
27132713
assert_identical(ds.set_index(x="x_var"), expected)
27142714

2715+
# Issue 3176: Ensure clear error message on key error.
2716+
with pytest.raises(ValueError) as excinfo:
2717+
ds.set_index(foo="bar")
2718+
assert str(excinfo.value) == "bar is not the name of an existing variable."
2719+
27152720
def test_reset_index(self):
27162721
ds = create_test_multiindex()
27172722
mindex = ds["x"].to_index()

0 commit comments

Comments
 (0)