Skip to content

BUG: IntervalIndex.get_loc/get_indexer wrong return value / error #25090

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

Closed
wants to merge 25 commits into from
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2aca389
Revert earlier change and use to_numpy
samuelsinayoko Feb 2, 2019
2d12d2f
Remove warning by using to_numpy
samuelsinayoko Feb 2, 2019
f357101
Make warning go away
samuelsinayoko Feb 2, 2019
7cc4c37
revert initial bugfix
samuelsinayoko Feb 2, 2019
8ec653a
Add test for contains in interval index categorical
samuelsinayoko Feb 2, 2019
878802e
Check get_loc on interval index raises KeyError
samuelsinayoko Feb 2, 2019
4dabe0e
Add test for get_indexer
samuelsinayoko Feb 2, 2019
564d88d
Add a test for get_indexer with different type
samuelsinayoko Feb 2, 2019
f4c43e3
Make first two tests pass
samuelsinayoko Feb 2, 2019
a09a07e
Make third test pass
samuelsinayoko Feb 2, 2019
6c887e6
remove commented out code
samuelsinayoko Feb 3, 2019
0a143f2
Improve error message
samuelsinayoko Feb 3, 2019
0730cd6
Rename, move and parametrize indexer test
samuelsinayoko Feb 3, 2019
246eb57
Use numpy_array_equal in indexer test
samuelsinayoko Feb 3, 2019
93f75ea
Refactor interval index get_loc test
samuelsinayoko Feb 4, 2019
268db81
Fix bug introduced in earlier commit
samuelsinayoko Feb 4, 2019
a5aa1e8
Add reminder comment to use raise from for python 3
samuelsinayoko Feb 6, 2019
d480872
Include key in error message.
samuelsinayoko Feb 6, 2019
6ed1080
Add larger interval range to test
samuelsinayoko Feb 6, 2019
120e2bc
get_loc should raise KeyError if the supplied key has the wrong type
samuelsinayoko Feb 6, 2019
2c48272
Only return -1 in get_indexer for incorrect values
samuelsinayoko Feb 10, 2019
02127ff
Better tests for get_indexer_errors
samuelsinayoko Feb 10, 2019
ad13d9e
Fix broken test in test_interval
samuelsinayoko Feb 11, 2019
0ff356c
Fix broken tests in test_concat
samuelsinayoko Feb 16, 2019
9f6b5c0
Merge remote-tracking branch 'upstream/master' into 23264
samuelsinayoko Apr 10, 2019
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 pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4615,6 +4615,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None,
else:
raise TypeError('must specify how or thresh')

#result = self._take(mask.to_numpy().nonzero()[0], axis=axis)
result = self.loc(axis=axis)[mask]

if inplace:
Expand Down
18 changes: 15 additions & 3 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -766,8 +766,13 @@ def get_loc(self, key, method=None):
key = Interval(left, right, key.closed)
else:
key = self._maybe_cast_slice_bound(key, 'left', None)

start, stop = self._find_non_overlapping_monotonic_bounds(key)
try:
Copy link
Member

Choose a reason for hiding this comment

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

You'll also need to do something similar in the else branch to cover the overlapping/non-monotonic case, e.g. I think something like pd.IntervalIndex.from_tuples([(1, 3), (2, 4), (0, 2)]).get_loc('foo') will still fail.

Copy link
Member

Choose a reason for hiding this comment

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

Maybe it should be the engine that should properly raise a KeyError? (eg the int64 engine does that)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I still need to look into @jorisvandenbossche's comment on raising the error in the engine itself (especially if that's the behaviour for int64), but I think I've addressed everything else.

Copy link
Member

Choose a reason for hiding this comment

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

@jorisvandenbossche : There is code in place within the engine that raises a KeyError, but strings queries fail before it gets there since the engine is expecting a scalar_t type (fused type consisting of numeric types) for key:

def get_loc(self, scalar_t key):

I'm not super well versed in Cython. Is there a graceful way to force this to raise a KeyError within the Cython code? Removing the scalar_t type gets a step further but still raises a TypeError as the code expects things to be comparable (probably some perf implications to removing it too).

Copy link
Member

Choose a reason for hiding this comment

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

Yeah, the other engines have the key as object typed, and then afterwards do a check of that.
But for me fine as well to leave that for now, and do the check here in the level above that. But on the long term would still be good to make the behaviour consistent throughout the different engines.

start, stop = self._find_non_overlapping_monotonic_bounds(key)
except TypeError:
# get loc should raise KeyError
Copy link
Contributor

Choose a reason for hiding this comment

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

Typo: .get_loc().

# if key is hashable but
# of an incorrect type
raise KeyError
Copy link
Contributor

Choose a reason for hiding this comment

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

This needs to be raise from, which is a Python 3 construct. To stay version-agnostic use six.raise_from.

Suggested change
raise KeyError
import six
...
try:
start, stop = self._find_non_overlapping_monotonic_bounds(key)
except TypeError as exc:
six.raise_from(KeyError('Key is hashable, but of an incorrect type'), exc)

Copy link
Member

@jschendel jschendel Feb 2, 2019

Choose a reason for hiding this comment

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

Is six.raise_from really necessary? I don't see us doing this anywhere else in the codebase?

Copy link
Contributor

Choose a reason for hiding this comment

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

we don't use python 3 only constructs yet, the existing is ok.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

OK, I've left the code as is but have improved the reported message as suggested by @rs2


if start is None or stop is None:
return slice(start, stop)
Expand Down Expand Up @@ -819,7 +824,14 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None):
return np.arange(len(self), dtype='intp')

if self.is_non_overlapping_monotonic:
start, stop = self._find_non_overlapping_monotonic_bounds(target)
try:
start, stop = (
self._find_non_overlapping_monotonic_bounds()
)
except TypeError:
# This is probably wrong
# but not sure what I should do here
Copy link
Contributor

Choose a reason for hiding this comment

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

¯\_(ツ)_/¯

return np.array([-1])
Copy link
Contributor

Choose a reason for hiding this comment

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

Please comment on the choice of -1.

Copy link
Member

Choose a reason for hiding this comment

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

This needs to be the same length as target and of intp dtype: np.repeat(np.intp(-1), len(target))


start_plus_one = start + 1
if not ((start_plus_one < stop).any()):
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/indexes/interval/test_interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,13 @@ def test_symmetric_difference(self, closed, sort):
result = index.symmetric_difference(other, sort=sort)
tm.assert_index_equal(result, expected)

def test_interval_range_get_indexer_with_different_input_type(self):
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 rename to test_get_indexer_errors and move to around line 618 where the other get_indexer tests are?

# not sure about this one
index = pd.interval_range(0, 1)
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 parametrize over index and include an non-monotonic/overlapping IntervalIndex, e.g. pd.IntervalIndex.from_tuples([(1, 3), (2, 4), (0, 2)])

# behaviour should be the same as Int64Index and return an
# array with values of -1
assert np.all(index.get_indexer(['gg']) == np.array([-1]))
Copy link
Member

Choose a reason for hiding this comment

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

use tm.assert_numpy_array_equal and make sure your expected is 'intp' dtype.


@pytest.mark.parametrize('op_name', [
'union', 'intersection', 'difference', 'symmetric_difference'])
@pytest.mark.parametrize("sort", [None, False])
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/indexing/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ def test_getitem_scalar(self):
result = s[cats[0]]
assert result == expected

def test_contains_interval_range(self):
"""Check we can use contains """
intervals = pd.interval_range(0.0, 1.0)
cats = pd.Categorical(intervals)
assert 'gg' not in cats

def test_slicing_directly(self):
cat = Categorical(["a", "b", "c", "d", "a", "b", "c"])
sliced = cat[3]
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -778,3 +778,9 @@ def test_loc_setitem_empty_append_raises(self):
msg = "cannot copy sequence with size 2 to array axis with dimension 0"
with pytest.raises(ValueError, match=msg):
df.loc[0:2, 'x'] = data

def test_loc_getitem_interval_index(self):
""" GH25087, test get_loc returns key error for interval indexes"""
idx = pd.interval_range(0, 1.0)
with pytest.raises(KeyError):
idx.get_loc('gg')
Copy link
Member

Choose a reason for hiding this comment

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

Instead of testing here, can you add this as a test case to test_get_loc_value in pandas/tests/indexes/interval/test_interval.py:

def test_get_loc_value(self):

Copy link
Contributor Author

@samuelsinayoko samuelsinayoko Feb 4, 2019

Choose a reason for hiding this comment

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

Good spot, I must say I wasn't completely clear about the distinction between indexes and indexing with regards to tests.
I've implemented your suggestion in 93f75ea.