Skip to content

DataFrame.drop silently does nothing if MultiIndex has duplicates #42801

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 6 commits into from
Jul 31, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ Fixed regressions
- Regression in :meth:`DataFrame.from_records` with empty records (:issue:`42456`)
- Fixed regression in :meth:`DataFrame.shift` where TypeError occurred when shifting DataFrame created by concatenation of slices and fills with values (:issue:`42719`)
- Regression in :meth:`DataFrame.agg` when the ``func`` argument returned lists and ``axis=1`` (:issue:`42727`)
- Regression in :meth:`DataFrame.drop` does nothing if :class:`MultiIndex` has duplicates and indexer is a tuple or list of tuples (:issue:`42771`)
- Fixed regression in comparisons between :class:`Timestamp` object and ``datetime64`` objects outside the implementation bounds for nanosecond ``datetime64`` (:issue:`42794`)
-

Expand Down
12 changes: 10 additions & 2 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@
ABCDataFrame,
ABCSeries,
)
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.inference import (
is_hashable,
is_nested_list_like,
)
from pandas.core.dtypes.missing import (
isna,
notna,
Expand Down Expand Up @@ -4182,6 +4185,7 @@ def _drop_axis(

# Case for non-unique axis
else:
is_tuple_labels = is_nested_list_like(labels) or isinstance(labels, tuple)
labels = ensure_object(com.index_labels_to_array(labels))
if level is not None:
if not isinstance(axis, MultiIndex):
Expand All @@ -4191,7 +4195,11 @@ 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":
elif (
isinstance(axis, MultiIndex)
and labels.dtype == "object"
and not is_tuple_labels
):
Copy link
Member

Choose a reason for hiding this comment

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

can you add a comment below this pointing back to the PR/issue

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

# 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)
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/frame/methods/test_drop.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,17 @@ def test_drop_with_non_unique_multiindex(self):
expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]]))
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("indexer", [("a", "a"), [("a", "a")]])
def test_drop_tuple_with_non_unique_multiindex(self, indexer):
# GH#42771
idx = MultiIndex.from_product([["a", "b"], ["a", "a"]])
df = DataFrame({"x": range(len(idx))}, index=idx)
result = df.drop(index=[("a", "a")])
expected = DataFrame(
{"x": [2, 3]}, index=MultiIndex.from_tuples([("b", "a"), ("b", "a")])
)
tm.assert_frame_equal(result, expected)

def test_drop_with_duplicate_columns(self):
df = DataFrame(
[[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]
Expand Down