Skip to content

Bug in xs raising KeyError for MultiIndex columns with droplevel False and list indexe #41789

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 4, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,7 @@ Deprecations
- Deprecated passing arguments as positional (other than ``filepath_or_buffer``) in :func:`read_csv` (:issue:`41485`)
- Deprecated passing arguments as positional in :meth:`DataFrame.drop` (other than ``"labels"``) and :meth:`Series.drop` (:issue:`41485`)
- Deprecated passing arguments as positional (other than ``filepath_or_buffer``) in :func:`read_table` (:issue:`41485`)

- Deprecated passing lists as ``key`` to :meth:`DataFrame.xs` and :meth:`Series.xs` with same length as ``level`` keyword (:issue:`41789`)

.. _whatsnew_130.deprecations.nuisance_columns:

Expand Down Expand Up @@ -947,6 +947,7 @@ Indexing
- Bug in :meth:`DataFrame.__setitem__` raising ``TypeError`` when using a str subclass as the column name with a :class:`DatetimeIndex` (:issue:`37366`)
- Bug in :meth:`PeriodIndex.get_loc` failing to raise ``KeyError`` when given a :class:`Period` with a mismatched ``freq`` (:issue:`41670`)
- Bug ``.loc.__getitem__`` with a :class:`UInt64Index` and negative-integer keys raising ``OverflowError`` instead of ``KeyError`` in some cases, wrapping around to positive integers in others (:issue:`41777`)
- Bug in :meth:`DataFrame.xs` and :meth:`Series.xs` accepting list as ``key`` and casting elements to different levels per index in list, now raises ``TypeError`` (:issue:`41760`)

Missing
^^^^^^^
Expand Down
12 changes: 12 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3756,6 +3756,18 @@ class animal locomotion
"""
axis = self._get_axis_number(axis)
labels = self._get_axis(axis)

if isinstance(key, list):
len_levels = 1 if level is None or is_scalar(level) else len(level)
if len(key) != len_levels:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this break any existing tests?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One test_xs_partial

Could deprecate this too, if you prefer?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah let's just deprecate entirely (prob easier to remember too)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

raise TypeError("Passing lists as key for xs is not allowed.")
warnings.warn(
"Passing lists as key for xs is deprecated and will be removed in a "
"future version. Pass key as a tuple instead.",
FutureWarning,
stacklevel=2,
)

if level is not None:
if not isinstance(labels, MultiIndex):
raise TypeError("Index must be a MultiIndex")
Expand Down
17 changes: 15 additions & 2 deletions pandas/tests/frame/indexing/test_xs.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ def test_xs_keep_level(self):
expected = df[:1]
tm.assert_frame_equal(result, expected)

result = df.xs([2008, "sat"], level=["year", "day"], drop_level=False)
with tm.assert_produces_warning(FutureWarning):
result = df.xs([2008, "sat"], level=["year", "day"], drop_level=False)
tm.assert_frame_equal(result, expected)

def test_xs_view(self, using_array_manager):
Expand Down Expand Up @@ -187,7 +188,11 @@ def test_xs_with_duplicates(self, key, level, multiindex_dataframe_random_data):
assert df.index.is_unique is False
expected = concat([frame.xs("one", level="second")] * 2)

result = df.xs(key, level=level)
if isinstance(key, list):
with tm.assert_produces_warning(FutureWarning):
result = df.xs(key, level=level)
else:
result = df.xs(key, level=level)
tm.assert_frame_equal(result, expected)

def test_xs_missing_values_in_index(self):
Expand Down Expand Up @@ -358,3 +363,11 @@ def test_xs_droplevel_false_view(self, using_array_manager):
df.iloc[0, 0] = 2
expected = DataFrame({"a": [1]})
tm.assert_frame_equal(result, expected)

def test_xs_list_indexer_droplevel_false(self):
# GH#41760
mi = MultiIndex.from_tuples([("x", "y", "a"), ("x", "z", "b"), ("v", "w", "c")])
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi)
msg = "Passing lists as key for xs is not allowed."
with pytest.raises(TypeError, match=msg):
df.xs(["x", "v"], drop_level=False, axis=1)
2 changes: 1 addition & 1 deletion pandas/tests/indexing/multiindex/test_partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def test_xs_partial(
)
df = DataFrame(np.random.randn(8, 4), index=index, columns=list("abcd"))

result = df.xs(["foo", "one"])
result = df.xs(("foo", "one"))
expected = df.loc["foo", "one"]
tm.assert_frame_equal(result, expected)

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/series/indexing/test_xs.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import numpy as np
import pytest

from pandas import (
MultiIndex,
Expand Down Expand Up @@ -69,3 +70,14 @@ def test_series_xs_droplevel_false(self):
),
)
tm.assert_series_equal(result, expected)

def test_xs_key_as_list(self):
# GH#41760
mi = MultiIndex.from_tuples([("a", "x")], names=["level1", "level2"])
ser = Series([1], index=mi)
msg = "Passing lists as key for xs is not allowed."
with pytest.raises(TypeError, match=msg):
ser.xs(["a", "x"], axis=0, drop_level=False)

with tm.assert_produces_warning(FutureWarning):
ser.xs(["a"], axis=0, drop_level=False)