Skip to content

BUG: Check types in Index.__contains__ (#22085) #22360

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 16 commits into from
Closed
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.24.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -658,6 +658,7 @@ Indexing
- Bug when indexing :class:`DatetimeIndex` with nanosecond resolution dates and timezones (:issue:`11679`)
- Bug where indexing with a Numpy array containing negative values would mutate the indexer (:issue:`21867`)
- ``Float64Index.get_loc`` now raises ``KeyError`` when boolean key passed. (:issue:`19087`)
- Bug in `scalar in Index` if scalar is a float while the ``Index`` is of integer dtype (:issue:`22085`)

Missing
^^^^^^^
Expand Down
3 changes: 3 additions & 0 deletions pandas/_libs/index.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ cdef class IndexEngine:
def __contains__(self, object val):
self._ensure_mapping_populated()
hash(val)
if (util.is_float_object(val) and isinstance(self, Int64Engine) and
int(val) != val):
return False
return val in self.mapping

cpdef get_value(self, ndarray arr, object key, object tz=None):
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2483,6 +2483,19 @@ def test_comparison_tzawareness_compat(self, op):
# TODO: implement _assert_tzawareness_compat for the reverse
# comparison with the Series on the left-hand side

def test_contains_with_float_val(self):
# GH#22085
index1 = pd.Index([0, 1, 2, 3])
index2 = pd.Index([0.1, 1.1, 2.2, 3.3])

assert 1.1 not in index1
assert 1.0 in index1
assert 1 in index1

assert 1.1 in index2
assert 1.0 not in index2
assert 1 not in index2


class TestIndexUtils(object):

Expand Down