Skip to content

Commit 9843926

Browse files
authored
CLN: clarify TypeError for IndexSlice argument to pd.xs (#35411)
1 parent dfa546e commit 9843926

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

doc/source/whatsnew/v1.2.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ Missing
134134
MultiIndex
135135
^^^^^^^^^^
136136

137-
-
137+
- Bug in :meth:`DataFrame.xs` when used with :class:`IndexSlice` raises ``TypeError`` with message `Expected label or tuple of labels` (:issue:`35301`)
138138
-
139139

140140
I/O

pandas/core/generic.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3492,7 +3492,10 @@ class animal locomotion
34923492

34933493
index = self.index
34943494
if isinstance(index, MultiIndex):
3495-
loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
3495+
try:
3496+
loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
3497+
except TypeError as e:
3498+
raise TypeError(f"Expected label or tuple of labels, got {key}") from e
34963499
else:
34973500
loc = self.index.get_loc(key)
34983501

pandas/tests/indexing/multiindex/test_xs.py

+22-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import numpy as np
22
import pytest
33

4-
from pandas import DataFrame, Index, MultiIndex, Series, concat, date_range
4+
from pandas import DataFrame, Index, IndexSlice, MultiIndex, Series, concat, date_range
55
import pandas._testing as tm
66
import pandas.core.common as com
77

@@ -220,6 +220,27 @@ def test_xs_level_series_slice_not_implemented(
220220
s[2000, 3:4]
221221

222222

223+
def test_xs_IndexSlice_argument_not_implemented():
224+
# GH 35301
225+
226+
index = MultiIndex(
227+
levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]],
228+
codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
229+
)
230+
231+
series = Series(np.random.randn(6), index=index)
232+
frame = DataFrame(np.random.randn(6, 4), index=index)
233+
234+
msg = (
235+
"Expected label or tuple of labels, got "
236+
r"\(\('foo', 'qux', 0\), slice\(None, None, None\)\)"
237+
)
238+
with pytest.raises(TypeError, match=msg):
239+
frame.xs(IndexSlice[("foo", "qux", 0), :])
240+
with pytest.raises(TypeError, match=msg):
241+
series.xs(IndexSlice[("foo", "qux", 0), :])
242+
243+
223244
def test_series_getitem_multiindex_xs():
224245
# GH6258
225246
dt = list(date_range("20130903", periods=3))

0 commit comments

Comments
 (0)