Skip to content
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

BUG: Bug in xs ignored droplevel #37776

Merged
merged 7 commits into from
Nov 13, 2020
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,7 @@ Indexing
- Bug in :meth:`Series.loc` and :meth:`DataFrame.loc` raises when numeric label was given for object :class:`Index` although label was in :class:`Index` (:issue:`26491`)
- Bug in :meth:`DataFrame.loc` returned requested key plus missing values when ``loc`` was applied to single level from :class:`MultiIndex` (:issue:`27104`)
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using a listlike indexer containing NA values (:issue:`37722`)
- Bug in :meth:`DataFrame.xs` ignored ``droplevel=False`` for columns (:issue:`19056`)

Missing
^^^^^^^
Expand Down
20 changes: 13 additions & 7 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3708,18 +3708,21 @@ class animal locomotion
return result

if axis == 1:
return self[key]
if drop_level:
return self[key]
index = self.columns
else:
index = self.index

index = self.index
if isinstance(index, MultiIndex):
try:
loc, new_index = self.index._get_loc_level(
loc, new_index = index._get_loc_level(
key, level=0, drop_level=drop_level
)
except TypeError as e:
raise TypeError(f"Expected label or tuple of labels, got {key}") from e
else:
loc = self.index.get_loc(key)
loc = index.get_loc(key)

if isinstance(loc, np.ndarray):
if loc.dtype == np.bool_:
Expand All @@ -3729,9 +3732,9 @@ class animal locomotion
return self._take_with_is_copy(loc, axis=axis)

if not is_scalar(loc):
new_index = self.index[loc]
new_index = index[loc]

if is_scalar(loc):
if is_scalar(loc) and axis == 0:
# In this case loc should be an integer
if self.ndim == 1:
# if we encounter an array-like and we only have 1 dim
Expand All @@ -3747,7 +3750,10 @@ class animal locomotion
name=self.index[loc],
dtype=new_values.dtype,
)

elif is_scalar(loc):
result = self.iloc[:, [loc]]
Copy link
Member

Choose a reason for hiding this comment

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

Until we implement #36195, this returns a copy and not a view. In followup can you make this self.iloc[:, slice(loc, loc + 1)], probably need to test that we're getting a view

Copy link
Member Author

Choose a reason for hiding this comment

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

elif axis == 1:
result = self.iloc[:, loc]
else:
Copy link
Contributor

Choose a reason for hiding this comment

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

can you make this part of the higher level if/else

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

result = self.iloc[loc]
result.index = new_index
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/frame/indexing/test_xs.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,3 +297,25 @@ def test_xs_levels_raises(self, klass):
msg = "Index must be a MultiIndex"
with pytest.raises(TypeError, match=msg):
obj.xs(0, level="as")

def test_xs_multiindex_droplevel_false(self):
# GH#19056
mi = MultiIndex.from_tuples(
[("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]
)
df = DataFrame([[1, 2, 3]], columns=mi)
result = df.xs("a", axis=1, drop_level=False)
jbrockmendel marked this conversation as resolved.
Show resolved Hide resolved
expected = DataFrame(
[[1, 2]],
columns=MultiIndex.from_tuples(
[("a", "x"), ("a", "y")], names=["level1", "level2"]
),
)
tm.assert_frame_equal(result, expected)

def test_xs_droplevel_false(self):
# GH#19056
df = DataFrame([[1, 2, 3]], columns=Index(["a", "b", "c"]))
result = df.xs("a", axis=1, drop_level=False)
expected = DataFrame({"a": [1]})
tm.assert_frame_equal(result, expected)
15 changes: 15 additions & 0 deletions pandas/tests/series/indexing/test_xs.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,18 @@ def test_series_getitem_multiindex_xs(xs):

result = ser.xs("20130903", level=1)
tm.assert_series_equal(result, expected)

def test_series_xs_droplevel_false(self):
# GH: 19056
mi = MultiIndex.from_tuples(
[("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"]
)
df = Series([1, 1, 1], index=mi)
result = df.xs("a", axis=0, drop_level=False)
expected = Series(
[1, 1],
index=MultiIndex.from_tuples(
[("a", "x"), ("a", "y")], names=["level1", "level2"]
),
)
tm.assert_series_equal(result, expected)