diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 9e1d2487b00fe..3643023637d4c 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -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 ^^^^^^^ diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 293f067810f27..7e5496179c580 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -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): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index c858b4d86cf5e..2a4f83d9cf913 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -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):