pandas-dev/pandas · #72260

PERF: don't build the engine in Index.is_monotonic_* to check its type

fangchenli · merged Nov 21, 20265 files · 78 + / 18 −
asv_bench/benchmarks/index_cached_properties.py4 + / 0 −
@@ -7,6 +7,7 @@ class IndexCache:      params = [         [+            "ArrowDateIndex",             "CategoricalIndex",             "DatetimeIndex",             "Float64Index",@@ -45,6 +46,9 @@ def setup(self, index_type):             self.idx = pd.Index(range(N), dtype="uint64")         elif index_type == "CategoricalIndex":             self.idx = pd.CategoricalIndex(range(N), range(N))+        elif index_type == "ArrowDateIndex":+            idx = pd.Index(range(N), dtype="int32[pyarrow]")+            self.idx = idx.astype("date32[pyarrow]")         else:             raise ValueError         assert len(self.idx) == N
doc/source/whatsnew/v3.2.0.rst1 + / 0 −
@@ -191,6 +191,7 @@ Other deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Performance improvement in :attr:`Index.is_monotonic_increasing`, :attr:`Index.is_monotonic_decreasing` and :attr:`Index.is_unique` for numeric and datetimelike data, and in indexing on large monotonic indexes (:issue:`72122`)+- Performance improvement in :attr:`Index.is_monotonic_increasing`, :attr:`Index.is_monotonic_decreasing` and their :class:`Series` counterparts for PyArrow-backed date, time and decimal data (:issue:`72260`) - Performance improvement in :meth:`DataFrame.apply` with ``raw=True`` (:issue:`66203`) - Performance improvement in :meth:`DataFrame.explode` when exploding multiple columns (:issue:`53967`) - Performance improvement in :func:`read_csv` with ``engine="c"`` across the board, in tokenizing and in the machinery shared by all column types; large uncompressed local files are additionally read in parallel across multiple CPU cores by default, see :ref:`above <whatsnew_310.enhancements.read_csv>` (:issue:`64347`, :issue:`64515`, :issue:`65350`, :issue:`66271`, :issue:`66272`, :issue:`66273`, :issue:`66274`, :issue:`66276`, :issue:`66798`, :issue:`68314`, :issue:`69632`, :issue:`69748`, :issue:`70140`)
pandas/core/indexes/base.py40 + / 18 −
@@ -2507,12 +2507,14 @@ def is_monotonic_increasing(self) -> bool:         >>> pd.Index([1, 3, 2]).is_monotonic_increasing         False         """-        if isinstance(self._values, ExtensionArray) and (-            type(self._engine) is libindex.ObjectEngine+        if (+            isinstance(self._values, ExtensionArray)+            and self._engine_target_is_object_cast+            and not isinstance(self.dtype, StringDtype)         ):             # For custom EAs we use ObjectEngine by default, which gets the EA as             # object ndarray -> use the EA's implementation directly instead of engine.-            # Subclasses of ObjectEngine (e.g. StringObjectEngine) are excluded.+            # Strings are excluded, they use StringObjectEngine.             return self._values._is_monotonic_increasing         return self._engine.is_monotonic_increasing @@ -2542,12 +2544,14 @@ def is_monotonic_decreasing(self) -> bool:         >>> pd.Index([3, 1, 2]).is_monotonic_decreasing         False         """-        if isinstance(self._values, ExtensionArray) and (-            type(self._engine) is libindex.ObjectEngine+        if (+            isinstance(self._values, ExtensionArray)+            and self._engine_target_is_object_cast+            and not isinstance(self.dtype, StringDtype)         ):             # For custom EAs we use ObjectEngine by default, which gets the EA as             # object ndarray -> use the EA's implementation directly instead of engine.-            # Subclasses of ObjectEngine (e.g. StringObjectEngine) are excluded.+            # Strings are excluded, they use StringObjectEngine.             return self._values._is_monotonic_decreasing         return self._engine.is_monotonic_decreasing @@ -5459,21 +5463,39 @@ def _get_engine_target(self) -> ArrayLike:             elif pa.types.is_duration(pa_type):                 vals = vals._to_timedeltaarray()                 return vals._ndarray.view("i8")-        if (-            type(self) is Index-            and isinstance(vals, ExtensionArray)-            and not isinstance(vals, BaseMaskedArray)-            and not (-                isinstance(vals, ArrowExtensionArray)-                and is_numeric_dtype(self.dtype)-                # Exclude decimal-                and self.dtype.kind != "O"-            )-        ):-            # TODO(ExtensionIndex): remove special-case, just use self._values+        if self._engine_target_is_object_cast:             return vals.astype(object)         return vals +    @final+    @cache_readonly+    def _engine_target_is_object_cast(self) -> bool:+        """+        Whether _get_engine_target casts our ExtensionArray to an object ndarray.++        Lets callers tell whether the engine would be an object engine without+        building it.+        """+        vals = self._values+        if (+            type(self) is not Index+            or not isinstance(vals, ExtensionArray)+            or isinstance(vals, (BaseMaskedArray, StringArray))+        ):+            return False+        if isinstance(vals, ArrowExtensionArray):+            dtype = self.dtype+            if dtype.kind in "Mm":+                import pyarrow as pa++                pa_type = vals._pa_array.type+                if pa.types.is_timestamp(pa_type) or pa.types.is_duration(pa_type):+                    return False+            # Numeric types other than decimal go to the engine as-is+            return not is_numeric_dtype(dtype) or dtype.kind == "O"+        # TODO(ExtensionIndex): remove special-case, just use self._values+        return True+     @final     def _get_join_target(self) -> np.ndarray:         """
pandas/tests/extension/decimal/test_decimal.py8 + / 0 −
@@ -466,6 +466,14 @@ def DecimalArray__array__(self, dtype=None):     df.at[0, "a"]  +def test_index_is_monotonic_does_not_build_engine():+    # GH#72260 the engine holds the array as Python objects+    idx = pd.Index(to_decimal([1, 2]))+    assert idx.is_monotonic_increasing+    assert not idx.is_monotonic_decreasing+    assert "_engine" not in idx._cache++ def test_to_numpy_keyword():     # test the extra keyword     values = [decimal.Decimal("1.1111"), decimal.Decimal("2.2222")]
pandas/tests/indexes/test_base.py25 + / 0 −
@@ -1995,6 +1995,31 @@ def test_is_monotonic_pyarrow_list_type():     assert not idx.is_monotonic_decreasing  +@pytest.mark.parametrize("pa_type", ["date32", "time32", "decimal128", "string"])+def test_is_monotonic_pyarrow_does_not_build_engine(pa_type):+    # GH#72260 the engine holds these types as Python objects+    pa = pytest.importorskip("pyarrow")+    pa_type = {+        "date32": pa.date32(),+        "time32": pa.time32("s"),+        "decimal128": pa.decimal128(10),+        "string": pa.string(),+    }[pa_type]+    arr = pa.array([1, 2], type=pa.int32()).cast(pa_type)+    idx = Index(pd.arrays.ArrowExtensionArray(arr))+    assert idx.is_monotonic_increasing+    assert not idx.is_monotonic_decreasing+    assert "_engine" not in idx._cache+++def test_is_monotonic_string_uses_engine(string_dtype_no_object):+    # GH#65919 the engine caches the result+    idx = Index(["a", "b"], dtype=string_dtype_no_object)+    assert idx.is_monotonic_increasing+    assert not idx.is_monotonic_decreasing+    assert "_engine" in idx._cache++ def test_index_equals_different_string_dtype(string_dtype_no_object):     # GH 61099     idx_obj = Index(["a", "b", "c"])