Skip to content

BUG: DataFrame.drop raising TypeError for string label with non-unique MultiIndex and no level provided #38220

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 9 commits into from
Dec 14, 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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ Missing
MultiIndex
^^^^^^^^^^

-
- Bug in :meth:`DataFrame.drop` raising ``TypeError`` when :class:`MultiIndex` is non-unique and no level is provided (:issue:`36293`)
-

I/O
Expand Down
4 changes: 4 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4182,6 +4182,10 @@ def _drop_axis(
# GH 18561 MultiIndex.drop should raise if label is absent
if errors == "raise" and indexer.all():
raise KeyError(f"{labels} not found in axis")
elif isinstance(axis, MultiIndex) and labels.dtype == "object":
# Set level to zero in case of MultiIndex and label is string,
# because isin can't handle strings for MultiIndexes GH#36293
indexer = ~axis.get_level_values(0).isin(labels)
else:
indexer = ~axis.isin(labels)
# Check if label doesn't exist along axis
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/frame/methods/test_drop.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,11 @@ def test_inplace_drop_and_operation(self, operation, inplace):
# Perform operation and check result
getattr(y, operation)(1)
tm.assert_frame_equal(df, expected)

def test_drop_with_non_unique_multiindex(self):
# GH#36293
mi = MultiIndex.from_arrays([["x", "y", "x"], ["i", "j", "i"]])
df = DataFrame([1, 2, 3], index=mi)
result = df.drop(index="x")
expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]]))
tm.assert_frame_equal(result, expected)