Skip to content

BUG: MultiIndex.drop does not raise if labels are partially found #37830

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 11 commits into from
Nov 26, 2020
Merged
Show file tree
Hide file tree
Changes from 9 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 @@ -617,6 +617,7 @@ Indexing
- Bug in :meth:`DataFrame.reindex` raising ``IndexingError`` wrongly for empty :class:`DataFrame` with ``tolerance`` not None or ``method="nearest"`` (:issue:`27315`)
- Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using listlike indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`)
- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`)
- Bug in :meth:`MultiIndex.drop` does not raise if labels are partially found (:issue:`37820`)
- Bug in :meth:`DataFrame.loc` did not raise ``KeyError`` when missing combination was given with ``slice(None)`` for remaining levels (:issue:`19556`)

Missing
Expand Down
9 changes: 6 additions & 3 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2084,7 +2084,7 @@ def drop(self, codes, level=None, errors="raise"):
Parameters
----------
codes : array-like
Must be a list of tuples
Must be a list of tuples when level is not specified
level : int or level name, default None
errors : str, default 'raise'

Expand Down Expand Up @@ -2139,10 +2139,13 @@ def _drop_from_level(self, codes, level, errors="raise"):
# are not nan and equal -1, this means they are missing in the index
nan_codes = isna(codes)
values[(np.equal(nan_codes, False)) & (values == -1)] = -2
if index.shape[0] == self.shape[0]:
values[np.equal(nan_codes, True)] = -2

not_found = codes[values == -2]
if len(not_found) != 0 and errors != "ignore":
raise KeyError(f"labels {not_found} not found in level")
mask = ~algos.isin(self.codes[i], values)
if mask.all() and errors != "ignore":
raise KeyError(f"labels {codes} not found in level")

return self[mask]

Expand Down
19 changes: 19 additions & 0 deletions pandas/tests/indexes/multi/test_drop.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,22 @@ def test_drop_with_nan_in_index(nulls_fixture):
msg = r"labels \[Timestamp\('2001-01-01 00:00:00'\)\] not found in level"
with pytest.raises(KeyError, match=msg):
mi.drop(pd.Timestamp("2001"), level="date")


def test_single_level_drop():
Copy link
Member

Choose a reason for hiding this comment

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

Could you rename to something like test_single_level_drop_partially_missing_elements?

Copy link
Contributor

Choose a reason for hiding this comment

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

@GYHHAHA can you do this one, ping on green.

# GH 37820

mi = MultiIndex.from_tuples([(1, 2), (2, 2), (3, 2)])
msg = r"labels \[4\] not found in level"
with pytest.raises(KeyError, match=msg):
mi.drop(4, level=0)
with pytest.raises(KeyError, match=msg):
mi.drop([1, 4], level=0)
msg = r"labels \[nan\] not found in level"
with pytest.raises(KeyError, match=msg):
mi.drop([np.nan], level=0)

mi = MultiIndex.from_tuples([(np.nan, 1), (1, 2)])
msg = r"labels \['a'\] not found in level"
with pytest.raises(KeyError, match=msg):
mi.drop([np.nan, 1, "a"], level=0)