-
-
Notifications
You must be signed in to change notification settings - Fork 18.1k
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
BUG: x in MultiIndex.drop(x) #19054
Conversation
tests? |
pandas/core/indexes/multi.py
Outdated
@@ -2120,6 +2120,12 @@ def _maybe_to_slice(loc): | |||
mask[loc] = True | |||
return mask | |||
|
|||
if isinstance(key, int): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
use is_integer rather than isinstance
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
add a comment here on what you are doing
idx = MultiIndex.from_product([[1, 2], [3, 4]]) | ||
assert 2 in idx | ||
idx = idx.drop(2) | ||
# drop implementation keeps 2 in the levels |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
blank line before the comment
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you test with a non-integer MI as well
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This comment made me realize that I had focused onto integers specifically when this should apply to all hashable keys (sorry). But, that would mean tuples would then be treated differently from how they currently are, e.g.:
In [88]: idx = pd.MultiIndex.from_product([[(1, 2), (2, 3)], [(3, 4), (4, 5)]])
In [89]: ((1, 2), (3, 4)) in idx
Out[89]: True
In [90]: (1, 2) in idx
Out[90]: False
In [91]: ((1, 2),) in idx
Out[91]: True
So, should it assume that a nested tuple like in In [89]
should be treated like tuples are currently treated but a non-nested tuple like in In [90]
should be treated like strings and ints?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Off the same vein, idx.drop((1, 2))
raises a KeyError and might warrant a separate issue since one would expect similar behavior to MultiIndex.from_product([[1, 2], [3, 4]]).drop(2)
, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This comment made me realize that I had focused onto integers specifically when this should apply to all hashable keys (sorry).
I think the idea should just be: any key k
which is not already a tuple must become one ((k,)
). The result will be, I think, consistent with current behavior (Out[89]:
, Out[90]:
, Out[91]:
), and you don't even need to check if key can be hashed - if it can't, it will just fail later on.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Off the same vein, idx.drop((1, 2)) raises a KeyError and might warrant a separate issue
Sure, in principle we could try with ((1,2),)
if (1,2)
is not found. However, I personally don't think it's a good idea, as it introduces ambiguity (we should be clear to users that a tuple in a MultiIndex
is first and foremost a key spanning across levels) and increases complexity.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Got it, thanks!
Doing it by simply turning non-tuples into tuples like so:
if not isinstance(key, tuple):
try:
return self.get_loc((key,))
except (LookupError, TypeError):
raise KeyError(key)
produces a performance warning for slightly larger multi-indeces:
In [31]: idx = pd.MultiIndex.from_product([[1, 2], [3, 4]])
In [32]: 2 in idx
Out[32]: True
In [33]: idx = pd.MultiIndex.from_product([[2, 1, 2], [3, 4]])
In [34]: 2 in idx
/home/avi/anaconda3/envs/pandas-dev/lib/python3.6/site-packages/IPython/terminal/ipapp.py:356: PerformanceWarning: indexing past lexsort depth may impact performance.
self.shell.mainloop()
Out[34]: True
Or we could use the fact that a key that has been dropped from a multi-index will return an empty slice when fed into the index's _get_level_indexer
like so:
if not isinstance(key, tuple):
loc = self._get_level_indexer(key, level=0)
if isinstance(loc, slice) and loc.start == loc.stop:
raise KeyError(key)
return _maybe_to_slice(loc)
which does not produce the performance warnings and is ~3 times faster and simply adds to what it is right now:
pandas/pandas/core/indexes/multi.py
Lines 2123 to 2125 in 4a8496b
if not isinstance(key, tuple): | |
loc = self._get_level_indexer(key, level=0) | |
return _maybe_to_slice(loc) |
but is potentially less clear (and more hacky?). Which one should I use?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I ended up using the faster one and added a comment to explain what's going on.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, I think it makes sense
Codecov Report
@@ Coverage Diff @@
## master #19054 +/- ##
=========================================
Coverage ? 91.51%
=========================================
Files ? 148
Lines ? 48783
Branches ? 0
=========================================
Hits ? 44642
Misses ? 4141
Partials ? 0
Continue to review full report at Codecov.
|
@@ -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: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what test exercises this?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
pandas/pandas/tests/test_multilevel.py
Line 1195 in 35b2aba
def test_stack_order_with_unsorted_levels(self): |
pandas/pandas/tests/frame/test_reshape.py
Line 136 in 35b2aba
def test_stack_mixed_level(self): |
pandas/pandas/tests/frame/test_reshape.py
Line 730 in 35b2aba
def test_stack_partial_multiIndex(self): |
These were the 3. And it looks like Travis doesn't have permalinks to specific lines like GitHub?
There was a problem hiding this comment.
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:
pandas/pandas/tests/frame/test_mutate_columns.py
Lines 186 to 198 in 35b2aba
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
.
@@ -195,7 +195,9 @@ def test_delitem_multiindex(self): | |||
|
|||
# xref: https://github.com/pandas-dev/pandas/issues/2770 | |||
# the 'A' is STILL in the columns! | |||
assert 'A' in df.columns | |||
# the above was changed, 'A' is no longer in columns |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you comment doesn't make sense here once the removed line is gone, can you clarify (and you can reference 2770), but make a nicer comment overall
@@ -705,6 +705,24 @@ def test_multiindex_symmetric_difference(self): | |||
result = idx ^ idx2 | |||
assert result.names == [None, None] | |||
|
|||
def test_multiindex_contains_dropped(self): | |||
# GH 19027 |
There was a problem hiding this comment.
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
cc @toobaz if any comments. |
It should no longer be needed since Additionally, if a boolean mask is returned, it can't possibly be of length 0 because that would require the |
How do I figure out which test the Travis build timed out on? It just says EDIT: Nevermind, this is the traceback of the highest exception but there's a bunch of sub-exceptions as well:
Not sure what's going on here... |
I think there's nothing you can do, I asked in Gitter to restart it. |
👍 |
thanks @gitavi |
git diff upstream/master -u -- "*.py" | flake8 --diff