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: x in MultiIndex.drop(x) #19054

Merged
merged 10 commits into from
Jan 10, 2018
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
3 changes: 2 additions & 1 deletion doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ Conversion
- Bug in :class:`Series` floor-division where operating on a scalar ``timedelta`` raises an exception (:issue:`18846`)
- Bug in :class:`FY5253Quarter`, :class:`LastWeekOfMonth` where rollback and rollforward behavior was inconsistent with addition and subtraction behavior (:issue:`18854`)
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
- Bug in :class:`Index` constructor with ``dtype=CategoricalDtype(...)`` where ``categories`` and ``ordered`` are not maintained (issue:`19032`)
- Bug in :class:`Series`` with ``dtype='timedelta64[ns]`` where addition or subtraction of ``TimedeltaIndex`` had results cast to ``dtype='int64'`` (:issue:`17250`)
- Bug in :class:`TimedeltaIndex` where division by a ``Series`` would return a ``TimedeltaIndex`` instead of a ``Series`` (issue:`19042`)
- Bug in :class:`Series` with ``dtype='timedelta64[ns]`` where addition or subtraction of ``TimedeltaIndex`` could return a ``Series`` with an incorrect name (issue:`19043`)
Expand All @@ -364,6 +364,7 @@ Indexing
- Bug in indexing non-scalar value from ``Series`` having non-unique ``Index`` will return value flattened (:issue:`17610`)
- Bug in :func:`DatetimeIndex.insert` where inserting ``NaT`` into a timezone-aware index incorrectly raised (:issue:`16357`)
- Bug in ``__setitem__`` when indexing a :class:`DataFrame` with a 2-d boolean ndarray (:issue:`18582`)
- Bug in :func:`MultiIndex.__contains__` where non-tuple keys would return ``True`` even if they had been dropped (:issue:`19027`)
- Bug in :func:`MultiIndex.set_labels` which would cause casting (and potentially clipping) of the new labels if the ``level`` argument is not 0 or a list like [0, 1, ... ] (:issue:`19057`)
- Bug in ``str.extractall`` when there were no matches empty :class:`Index` was returned instead of appropriate :class:`MultiIndex` (:issue:`19034`)

Expand Down
5 changes: 5 additions & 0 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2123,6 +2123,11 @@ def _maybe_to_slice(loc):

if not isinstance(key, tuple):
loc = self._get_level_indexer(key, level=0)

# _get_level_indexer returns an empty slice if the key has
# been dropped from the MultiIndex
if isinstance(loc, slice) and loc.start == loc.stop:
raise KeyError(key)
return _maybe_to_slice(loc)

keylen = len(key)
Expand Down
11 changes: 6 additions & 5 deletions pandas/core/reshape/reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,11 @@ def _convert_level_number(level_num, columns):
levsize = len(level_labels)
drop_cols = []
for key in unique_groups:
loc = this.columns.get_loc(key)
try:
Copy link
Contributor

Choose a reason for hiding this comment

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

what test exercises this?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

def test_stack_order_with_unsorted_levels(self):

def test_stack_mixed_level(self):

def test_stack_partial_multiIndex(self):

These were the 3. And it looks like Travis doesn't have permalinks to specific lines like GitHub?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Also just took a look at the test that caused most of the builds to fail:

del df['A']
assert len(df.columns) == 2
# A still in the levels, BUT get a KeyError if trying
# to delete
assert ('A', ) not in df.columns
with pytest.raises(KeyError):
del df[('A',)]
# xref: https://github.com/pandas-dev/pandas/issues/2770
# the 'A' is STILL in the columns!
assert 'A' in df.columns

and we just changed this so I'll go ahead and negate the assert.

loc = this.columns.get_loc(key)
except KeyError:
drop_cols.append(key)
continue

# can make more efficient?
# we almost always return a slice
Expand All @@ -639,10 +643,7 @@ def _convert_level_number(level_num, columns):
else:
slice_len = loc.stop - loc.start

if slice_len == 0:
drop_cols.append(key)
continue
elif slice_len != levsize:
if slice_len != levsize:
chunk = this.loc[:, this.columns[loc]]
chunk.columns = level_vals.take(chunk.columns.labels[-1])
value_slice = chunk.reindex(columns=level_vals_used).values
Expand Down
7 changes: 4 additions & 3 deletions pandas/tests/frame/test_mutate_columns.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,10 @@ def test_delitem_multiindex(self):
with pytest.raises(KeyError):
del df[('A',)]

# xref: https://github.com/pandas-dev/pandas/issues/2770
# the 'A' is STILL in the columns!
assert 'A' in df.columns
# behavior of dropped/deleted MultiIndex levels changed from
# GH 2770 to GH 19027: MultiIndex no longer '.__contains__'
# levels which are dropped/deleted
assert 'A' not in df.columns
with pytest.raises(KeyError):
del df['A']

Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/indexing/test_multiindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,26 @@ def test_multiindex_symmetric_difference(self):
result = idx ^ idx2
assert result.names == [None, None]

def test_multiindex_contains_dropped(self):
# GH 19027
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 add a comment

# test that dropped MultiIndex levels are not in the MultiIndex
# despite continuing to be in the MultiIndex's levels
idx = MultiIndex.from_product([[1, 2], [3, 4]])
assert 2 in idx
idx = idx.drop(2)

# drop implementation keeps 2 in the levels
assert 2 in idx.levels[0]
# but it should no longer be in the index itself
assert 2 not in idx

# also applies to strings
idx = MultiIndex.from_product([['a', 'b'], ['c', 'd']])
assert 'a' in idx
idx = idx.drop('a')
assert 'a' in idx.levels[0]
assert 'a' not in idx


class TestMultiIndexSlicers(object):

Expand Down