pandas-dev/pandas · #70622

ENH: add sum/prod/mean/median/std/var/sem/skew/kurt to Index (GH#50021)

jbrockmendel · merged Nov 29, 20265 files · 744 + / 5 −
doc/source/reference/indexing.rst9 + / 0 −
@@ -67,6 +67,15 @@ Modifying and computations    Index.is_    Index.min    Index.max+   Index.sum+   Index.prod+   Index.mean+   Index.median+   Index.std+   Index.var+   Index.sem+   Index.skew+   Index.kurt    Index.reindex    Index.rename    Index.repeat
doc/source/whatsnew/v3.2.0.rst3 + / 0 −
@@ -28,6 +28,7 @@ enhancement2  Other enhancements ^^^^^^^^^^^^^^^^^^+- :class:`Index` now supports the reductions :meth:`~Index.sum`, :meth:`~Index.prod`, :meth:`~Index.mean`, :meth:`~Index.median`, :meth:`~Index.std`, :meth:`~Index.var`, :meth:`~Index.sem`, :meth:`~Index.skew`, and :meth:`~Index.kurt`, matching :class:`Series` (:issue:`50021`) - :class:`Series`, :class:`DataFrame`, :class:`Index`, and :class:`ExtensionArray` now support the ``minimummaximum`` ufunc reduction backing ``np.minmax`` (NumPy 2.6+), returning the same results as ``np.minimum.reduce`` and ``np.maximum.reduce`` (:issue:`71380`) - :func:`numpy.delete` on an :class:`ExtensionArray`, and :func:`numpy.concatenate` on :class:`ExtensionArray` objects of the same dtype, now return an :class:`ExtensionArray` of that dtype instead of a NumPy array (:issue:`26380`) - :func:`read_csv` and :func:`read_table` with ``sep=None`` now sniff the separator with the C engine instead of falling back to the slower python engine (:issue:`9645`)@@ -144,6 +145,7 @@ Other API changes - :meth:`DataFrame.query` now raises a ``ValueError`` when the expression does not evaluate to a boolean array, instead of silently using the result as row labels; use :attr:`DataFrame.loc` for label selection (:issue:`8560`) - :meth:`DataFrame.to_html` no longer emits the invalid HTML attribute ``halign="left"`` on :class:`MultiIndex` column headers; browsers ignored it, so rendering is unchanged (:issue:`39951`) - Arithmetic with ``bool[pyarrow]`` data now matches the NumPy ``bool`` and nullable ``boolean`` dtypes instead of raising ``TypeError``: ``+``/``*`` between booleans act as logical or/and, ``/``, ``//`` and ``**`` raise ``NotImplementedError``, and booleans combined with integer or float data act as numbers (:issue:`63064`)+- ``np.sum``, ``np.prod``, ``np.mean``, ``np.std`` and ``np.var`` on an :class:`Index` no longer accept ``where`` (or ``mean`` for ``np.std`` and ``np.var``), as they now call the new :class:`Index` reduction methods (:issue:`50021`) - ``range`` values are now displayed as ``range(0, 3)`` rather than as the tuple ``(0, 1, 2)``, matching :class:`.Styler` (:issue:`44799`)  .. ---------------------------------------------------------------------------@@ -182,6 +184,7 @@ Other deprecations - Deprecated the ``closed`` keyword in :func:`timedelta_range`; use ``inclusive`` instead, which also accepts ``"neither"``, as in :func:`date_range` (:issue:`40245`) - Deprecated the ``columns`` keyword in :meth:`Series.drop`, which was silently ignored; use ``index`` or ``labels`` instead (:issue:`39509`) - Deprecated the ``include_start`` and ``include_end`` keywords in :meth:`DatetimeIndex.indexer_between_time`; use ``inclusive`` instead, as in :meth:`DataFrame.between_time` (:issue:`40245`)+- Deprecated the behavior of ``np.sum``, ``np.prod``, ``np.mean``, ``np.std`` and ``np.var`` on an :class:`Index`; in a future version these will call the new :class:`Index` methods, which skip missing values and do not accept numpy-only keywords such as ``dtype``, matching :class:`Series`. Use ``np.asarray(index)`` to keep the current behavior (:issue:`50021`) - Deprecated constructing a :class:`DataFrame` column, :class:`Index` or :func:`array` from a NumPy structured (compound) array, and casting to a compound dtype with :meth:`DataFrame.astype`, :meth:`Series.astype` or :func:`array`; these will raise in a future version, as the :class:`Series` constructor already does. Use ``pd.DataFrame(arr)`` for one column per field or ``arr.astype(object)`` for tuples (:issue:`4464`, :issue:`49388`, :issue:`60108`) - Deprecated the undocumented ``how="begin"`` and ``how="finish"`` aliases in :meth:`Period.asfreq`, :meth:`Period.to_timestamp`, and the ``asfreq`` and ``to_timestamp`` methods of other period-holding objects; use ``"start"`` and ``"end"`` instead (:issue:`49132`) 
pandas/core/indexes/base.py557 + / 1 −
@@ -9,7 +9,9 @@ import functools from itertools import zip_longest import operator+import os import reprlib+import sys from typing import (     TYPE_CHECKING,     Any,@@ -69,6 +71,7 @@     find_stack_level,     rewrite_exception, )+from pandas.util._validators import validate_min_count  from pandas.core.dtypes.astype import (     astype_array,@@ -214,6 +217,7 @@         JoinHow,         Level,         NaPosition,+        NpDtype,         ReindexMethod,         Shape,         SliceType,@@ -1009,7 +1013,11 @@ def __array_ufunc__(                 self, ufunc, method, *inputs, **kwargs             ) -        if method == "reduce":+        if method == "reduce" and not (+            # Index.sum/prod reject numpy-only keywords such as dtype, GH#50021+            ufunc in (np.add, np.multiply)+            and any(val is not None for key, val in kwargs.items() if key != "axis")+        ):             result = arraylike.dispatch_reduction_ufunc(                 self, ufunc, method, *inputs, **kwargs             )@@ -8323,6 +8331,554 @@ def max(             nanops.nanmax(self._values, skipna=skipna), object_with_dtype=self         ) +    @final+    def _validate_numpy_reduction(+        self,+        name: str_t,+        validate: Callable[..., None],+        axis: AxisInt | None,+        numpy_kwargs: dict[str_t, Any],+        **op_kwargs: Any,+    ) -> Any:+        """+        Validate numpy-compat arguments, or return the deprecated numpy result.++        Returns ``lib.no_default`` when the caller should compute its own result.+        """+        if numpy_kwargs["out"] is lib.no_default:+            # numpy always passes ``out``, so this is a direct call+            numpy_kwargs["out"] = None+        else:+            result = self._deprecated_numpy_reduction(+                name, axis, numpy_kwargs, **op_kwargs+            )+            if result is not lib.no_default:+                return result+        validate((), numpy_kwargs, fname=name)+        nv.validate_minmax_axis(axis)+        return lib.no_default++    @final+    def _deprecated_numpy_reduction(+        self,+        name: str_t,+        axis: AxisInt | None,+        numpy_kwargs: dict[str_t, Any],+        **op_kwargs: Any,+    ) -> Any:+        """+        Return numpy's old result for ``np.<name>(index)``, or ``lib.no_default``.++        Before GH#50021 numpy did not call the Index method, so did not skip+        missing values and accepted numpy-only keywords.+        """+        if self._is_multi:+            return lib.no_default+        changed = {+            key: val+            for key, val in numpy_kwargs.items()+            if val is not None and val is not False+        }+        if (+            not changed+            and not self.hasnans+            and not isinstance(self.dtype, CategoricalDtype)+        ):+            # numpy computes mean/std/var on numeric categoricals; Categorical raises+            return lib.no_default+        try:+            if name in ("sum", "prod"):+                # the call numpy made when Index had no sum/prod+                ufunc = np.add if name == "sum" else np.multiply+                reduce_kwargs: dict[str_t, Any] = {+                    "axis": axis,+                    "dtype": None,+                    **changed,+                }+                # error: Argument 1 to "reduce" of "_UFunc_Nin2_Nout1" has+                # incompatible type "ExtensionArray | ndarray[...]"+                result = ufunc.reduce(+                    self._values,  # type: ignore[arg-type]+                    **reduce_kwargs,+                )+                result = maybe_unbox_numpy_scalar(+                    lib.item_from_zerodim(result), object_with_dtype=self+                )+            else:+                result = getattr(np, name)(+                    np.asarray(self), axis=axis, **changed, **op_kwargs+                )+        except TypeError:+            # numpy raised here too, so there is no behavior to keep+            return lib.no_default++        # find_stack_level stops at the numpy function that called the method+        stacklevel = find_stack_level()+        frame = sys._getframe(stacklevel - 1)+        numpy_dir = os.path.dirname(np.__file__) + os.sep+        while frame.f_back is not None and frame.f_code.co_filename.startswith(+            numpy_dir+        ):+            frame = frame.f_back+            stacklevel += 1+        if isinstance(self.dtype, CategoricalDtype):+            reason = "raises for categorical dtype"+        else:+            reason = (+                "skips missing values and does not accept numpy-only keywords "+                "such as 'dtype'"+            )+        warnings.warn(+            f"In a future version, np.{name}(index) will call Index.{name}, which "+            f"{reason}, matching Series. Use np.{name}(np.asarray(index)) to keep "+            "the current behavior.",+            Pandas4Warning,+            stacklevel=stacklevel,+        )+        return result++    def sum(+        self,+        *,+        axis: AxisInt | None = None,+        dtype: NpDtype | None = None,+        out: lib.NoDefault | None = lib.no_default,+        initial: None = None,+        keepdims: bool = False,+        skipna: bool = True,+        min_count: int = 0,+    ) -> Any:+        """+        Return the sum of the values in the Index.++        NA/null values are excluded by default.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        dtype, out, initial : None+            Not implemented; kept for compatibility with :func:`numpy.sum`,+            which calls this method. Must be left at the default.+        keepdims : bool, default False+            Not implemented; must be left at the default.+        skipna : bool, default True+            Exclude NA/null values when computing the result.+        min_count : int, default 0+            The required number of valid values to perform the operation. If fewer+            than ``min_count`` non-NA values are present the result will be NA.++        Returns+        -------+        scalar+            The sum of the values.++        See Also+        --------+        Index.prod : Return the product of the values.+        Series.sum : Return the sum of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3]).sum()+        6++        >>> pd.Index([1.0, np.nan]).sum(min_count=2)+        nan+        """+        result = self._validate_numpy_reduction(+            "sum",+            nv.validate_sum,+            axis,+            {"dtype": dtype, "out": out, "keepdims": keepdims, "initial": initial},+        )+        if result is not lib.no_default:+            return result+        min_count = validate_min_count(min_count)+        result = self.array._reduce("sum", skipna=skipna, min_count=min_count)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def prod(+        self,+        *,+        axis: AxisInt | None = None,+        dtype: NpDtype | None = None,+        out: lib.NoDefault | None = lib.no_default,+        initial: None = None,+        keepdims: bool = False,+        skipna: bool = True,+        min_count: int = 0,+    ) -> Any:+        """+        Return the product of the values in the Index.++        NA/null values are excluded by default.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        dtype, out, initial : None+            Not implemented; kept for compatibility with :func:`numpy.prod`,+            which calls this method. Must be left at the default.+        keepdims : bool, default False+            Not implemented; must be left at the default.+        skipna : bool, default True+            Exclude NA/null values when computing the result.+        min_count : int, default 0+            The required number of valid values to perform the operation. If fewer+            than ``min_count`` non-NA values are present the result will be NA.++        Returns+        -------+        scalar+            The product of the values.++        See Also+        --------+        Index.sum : Return the sum of the values.+        Series.prod : Return the product of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3, 4]).prod()+        24+        """+        result = self._validate_numpy_reduction(+            "prod",+            nv.validate_prod,+            axis,+            {"dtype": dtype, "out": out, "keepdims": keepdims, "initial": initial},+        )+        if result is not lib.no_default:+            return result+        min_count = validate_min_count(min_count)+        result = self.array._reduce("prod", skipna=skipna, min_count=min_count)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def mean(+        self,+        *,+        axis: AxisInt | None = None,+        dtype: NpDtype | None = None,+        out: lib.NoDefault | None = lib.no_default,+        keepdims: bool = False,+        skipna: bool = True,+    ) -> Any:+        """+        Return the mean of the values in the Index.++        NA/null values are excluded by default.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        dtype, out : None+            Not implemented; kept for compatibility with :func:`numpy.mean`,+            which calls this method. Must be left at the default.+        keepdims : bool, default False+            Not implemented; must be left at the default.+        skipna : bool, default True+            Exclude NA/null values when computing the result.++        Returns+        -------+        scalar+            The mean of the values.++        See Also+        --------+        Index.median : Return the median of the values.+        Series.mean : Return the mean of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3, 4]).mean()+        2.5+        """+        result = self._validate_numpy_reduction(+            "mean",+            nv.validate_mean,+            axis,+            {"dtype": dtype, "out": out, "keepdims": keepdims},+        )+        if result is not lib.no_default:+            return result+        result = self.array._reduce("mean", skipna=skipna)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def median(+        self,+        *,+        axis: AxisInt | None = None,+        skipna: bool = True,+        **kwargs: Any,+    ) -> Any:+        """+        Return the median of the values in the Index.++        NA/null values are excluded by default.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        skipna : bool, default True+            Exclude NA/null values when computing the result.+        **kwargs+            Additional keywords for compatibility with numpy.++        Returns+        -------+        scalar+            The median of the values.++        See Also+        --------+        Index.mean : Return the mean of the values.+        Series.median : Return the median of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 10]).median()+        2.0+        """+        nv.validate_median((), kwargs)+        nv.validate_minmax_axis(axis)+        result = self.array._reduce("median", skipna=skipna)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def std(+        self,+        *,+        axis: AxisInt | None = None,+        dtype: NpDtype | None = None,+        out: lib.NoDefault | None = lib.no_default,+        keepdims: bool = False,+        ddof: int = 1,+        skipna: bool = True,+    ) -> Any:+        """+        Return the sample standard deviation of the values in the Index.++        Normalized by N-1 by default. This can be changed using ``ddof``.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        dtype, out : None+            Not implemented; kept for compatibility with :func:`numpy.std`,+            which calls this method. Must be left at the default.+        keepdims : bool, default False+            Not implemented; must be left at the default.+        ddof : int, default 1+            Delta Degrees of Freedom. The divisor used in calculations is+            ``N - ddof``, where ``N`` represents the number of elements.+        skipna : bool, default True+            Exclude NA/null values when computing the result.++        Returns+        -------+        scalar+            The standard deviation of the values.++        See Also+        --------+        Index.var : Return the variance of the values.+        Series.std : Return the standard deviation of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3]).std()+        1.0+        """+        result = self._validate_numpy_reduction(+            "std",+            nv.validate_stat_ddof_func,+            axis,+            {"dtype": dtype, "out": out, "keepdims": keepdims},+            ddof=ddof,+        )+        if result is not lib.no_default:+            return result+        result = self.array._reduce("std", skipna=skipna, ddof=ddof)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def var(+        self,+        *,+        axis: AxisInt | None = None,+        dtype: NpDtype | None = None,+        out: lib.NoDefault | None = lib.no_default,+        keepdims: bool = False,+        ddof: int = 1,+        skipna: bool = True,+    ) -> Any:+        """+        Return the unbiased variance of the values in the Index.++        Normalized by N-1 by default. This can be changed using ``ddof``.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        dtype, out : None+            Not implemented; kept for compatibility with :func:`numpy.var`,+            which calls this method. Must be left at the default.+        keepdims : bool, default False+            Not implemented; must be left at the default.+        ddof : int, default 1+            Delta Degrees of Freedom. The divisor used in calculations is+            ``N - ddof``, where ``N`` represents the number of elements.+        skipna : bool, default True+            Exclude NA/null values when computing the result.++        Returns+        -------+        scalar+            The variance of the values.++        See Also+        --------+        Index.std : Return the standard deviation of the values.+        Series.var : Return the variance of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3]).var()+        1.0+        """+        result = self._validate_numpy_reduction(+            "var",+            nv.validate_stat_ddof_func,+            axis,+            {"dtype": dtype, "out": out, "keepdims": keepdims},+            ddof=ddof,+        )+        if result is not lib.no_default:+            return result+        result = self.array._reduce("var", skipna=skipna, ddof=ddof)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def sem(+        self,+        *,+        axis: AxisInt | None = None,+        ddof: int = 1,+        skipna: bool = True,+    ) -> Any:+        """+        Return the unbiased standard error of the mean of the values in the Index.++        Normalized by N-1 by default. This can be changed using ``ddof``.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        ddof : int, default 1+            Delta Degrees of Freedom. The divisor used in calculations is+            ``N - ddof``, where ``N`` represents the number of elements.+        skipna : bool, default True+            Exclude NA/null values when computing the result.++        Returns+        -------+        scalar+            The standard error of the mean.++        See Also+        --------+        Index.std : Return the standard deviation of the values.+        Series.sem : Return the standard error of the mean of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3]).sem()+        0.5773502691896258+        """+        nv.validate_minmax_axis(axis)+        result = self.array._reduce("sem", skipna=skipna, ddof=ddof)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def skew(+        self,+        *,+        axis: AxisInt | None = None,+        skipna: bool = True,+    ) -> Any:+        """+        Return the unbiased skew of the values in the Index.++        Normalized by N-1.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        skipna : bool, default True+            Exclude NA/null values when computing the result.++        Returns+        -------+        scalar+            The skew of the values.++        See Also+        --------+        Index.kurt : Return the kurtosis of the values.+        Series.skew : Return the skew of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 3]).skew()+        0.0+        """+        nv.validate_minmax_axis(axis)+        result = self.array._reduce("skew", skipna=skipna)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)++    def kurt(+        self,+        *,+        axis: AxisInt | None = None,+        skipna: bool = True,+    ) -> Any:+        """+        Return the unbiased kurtosis of the values in the Index.++        Kurtosis obtained using Fisher's definition of kurtosis (kurtosis of+        normal == 0.0). Normalized by N-1.++        Parameters+        ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        skipna : bool, default True+            Exclude NA/null values when computing the result.++        Returns+        -------+        scalar+            The kurtosis of the values.++        See Also+        --------+        Index.skew : Return the skew of the values.+        Series.kurt : Return the kurtosis of the values of a Series.++        Examples+        --------+        >>> pd.Index([1, 2, 2, 3]).kurt()+        1.5+        """+        nv.validate_minmax_axis(axis)+        result = self.array._reduce("kurt", skipna=skipna)+        return maybe_unbox_numpy_scalar(result, object_with_dtype=self)+     # --------------------------------------------------------------------      @final
pandas/core/indexes/datetimelike.py21 + / 4 −
@@ -97,8 +97,10 @@      from pandas._typing import (         Axis,+        AxisInt,         Frequency,         JoinHow,+        NpDtype,         TimeUnit,         npt,     )@@ -115,7 +117,15 @@ class DatetimeIndexOpsMixin(NDArrayBackedExtensionIndex, ABC):     _data: DatetimeArray | TimedeltaArray | PeriodArray     _warn_quarter: bool = True -    def mean(self, *, skipna: bool = True, axis: int | None = 0):+    def mean(+        self,+        *,+        axis: AxisInt | None = None,+        dtype: NpDtype | None = None,+        out: lib.NoDefault | None = None,+        keepdims: bool = False,+        skipna: bool = True,+    ) -> Any:         """         Return the mean value of the Array. @@ -124,10 +134,15 @@ def mean(self, *, skipna: bool = True, axis: int | None = 0):          Parameters         ----------+        axis : {None, 0}+            Unused. Parameter needed for compatibility with numpy.+        dtype, out : None+            Not implemented; kept for compatibility with :func:`numpy.mean`,+            which calls this method. Must be left at the default.+        keepdims : bool, default False+            Not implemented; must be left at the default.         skipna : bool, default True             Whether to ignore any NaT elements.-        axis : int, optional, default 0-            Axis for the function to be applied on.          Returns         -------@@ -163,7 +178,9 @@ def mean(self, *, skipna: bool = True, axis: int | None = 0):         >>> tdelta_idx.mean()         Timedelta('2 days 00:00:00')         """-        return self._data.mean(skipna=skipna, axis=axis)+        nv.validate_mean((), {"dtype": dtype, "out": out, "keepdims": keepdims})+        nv.validate_minmax_axis(axis)+        return self._data.mean(skipna=skipna)      @property     def freq(self) -> BaseOffset | None:
pandas/tests/reductions/test_reductions.py154 + / 0 −
@@ -4,6 +4,7 @@     timedelta, ) from decimal import Decimal+import re  import numpy as np import pytest@@ -276,6 +277,38 @@ def test_nan_int_timedelta_sum(self):         tm.assert_series_equal(result, expected)  +INDEX_REDUCTIONS = [+    "sum",+    "prod",+    "mean",+    "median",+    "std",+    "var",+    "sem",+    "skew",+    "kurt",+]+++def check_reduction_matches_series(index, opname, skipna):+    # not to_series, which infers str from object dtype+    ser = pd.Series(index)+    warn = None+    if index.dtype.kind == "c" and opname == "median":+        warn = Pandas4Warning+    try:+        with tm.assert_produces_warning(warn, match="deprecated on complex data"):+            expected = getattr(ser, opname)(skipna=skipna)+    except TypeError as err:+        with pytest.raises(TypeError, match=re.escape(str(err))):+            getattr(index, opname)(skipna=skipna)+        return+    with tm.assert_produces_warning(warn, match="deprecated on complex data"):+        result = getattr(index, opname)(skipna=skipna)+    assert type(result) is type(expected)+    tm.assert_almost_equal(result, expected)++ class TestIndexReductions:     # Note: the name TestIndexReductions indicates these tests     #  were moved from an Index-specific test file, _not_ that these tests are@@ -633,6 +666,105 @@ def test_min_max_multiindex_result_type(self, op, monotonic, using_python_scalar             assert isinstance(result[0], np.integer)             assert isinstance(result[1], np.floating) +    @pytest.mark.parametrize("opname", INDEX_REDUCTIONS)+    @pytest.mark.parametrize("skipna", [True, False])+    def test_reductions_match_series(self, index_flat, opname, skipna):+        # GH#50021+        check_reduction_matches_series(index_flat, opname, skipna)++    @pytest.mark.parametrize("opname", INDEX_REDUCTIONS)+    @pytest.mark.parametrize("skipna", [True, False])+    def test_reductions_match_series_with_missing(+        self, index_with_missing, opname, skipna+    ):+        # GH#50021+        check_reduction_matches_series(index_with_missing, opname, skipna)++    @pytest.mark.parametrize("opname", INDEX_REDUCTIONS)+    @pytest.mark.parametrize("skipna", [True, False])+    def test_reductions_match_series_float_nan(self, opname, skipna):+        # GH#50021 index_with_missing excludes numpy float+        idx = pd.Index([1.0, np.nan, 3.0, 7.0])+        check_reduction_matches_series(idx, opname, skipna)++    @pytest.mark.parametrize("opname", INDEX_REDUCTIONS)+    def test_reductions_multiindex_raise(self, opname):+        # GH#50021+        mi = pd.MultiIndex.from_arrays([[1, 2], [3, 4]])+        with pytest.raises(ValueError, match="MultiIndex has no single backing array"):+            getattr(mi, opname)()++    def test_reduction_kwargs(self):+        # GH#50021+        idx = pd.Index([1.0, np.nan, 3.0])+        assert np.isnan(idx.sum(min_count=3))+        assert idx.var(ddof=0) == 1.0+        with pytest.raises(ValueError, match="`axis` must be less than"):+            idx.sum(axis=1)+        with pytest.raises(TypeError, match="unexpected keyword argument"):+            idx.mean(foo=1)+        with pytest.raises(ValueError, match="the 'dtype' parameter is not supported"):+            idx.sum(dtype="float64")++    @pytest.mark.parametrize("func", [np.sum, np.prod, np.mean, np.std, np.var])+    def test_numpy_reductions_dispatch(self, func):+        # GH#50021+        idx = pd.Index([1.0, 2.0, 4.0])+        with tm.assert_produces_warning(None):+            result = func(idx)+        assert result == func(idx.to_series())++    @pytest.mark.parametrize("func", [np.sum, np.prod, np.mean, np.std, np.var])+    @pytest.mark.parametrize("dtype", ["float64", "Int64"])+    def test_numpy_reductions_missing_deprecated(self, func, dtype):+        # GH#50021 the Index methods skip missing values, numpy does not+        idx = pd.Index([1, None, 3], dtype=dtype)+        msg = rf"np\.{func.__name__}\(index\) will call Index\.{func.__name__}"+        with tm.assert_produces_warning(Pandas4Warning, match=msg):+            result = func(idx)+        assert pd.isna(result)++    @pytest.mark.parametrize("func", [np.mean, np.std, np.var])+    def test_numpy_reductions_categorical_deprecated(self, func):+        # GH#50021 numpy computes these, Index.mean/std/var raise for categorical+        idx = pd.CategoricalIndex([1, 2, 4])+        msg = (+            rf"np\.{func.__name__}\(index\) will call Index\.{func.__name__}, "+            "which raises for categorical dtype"+        )+        with tm.assert_produces_warning(Pandas4Warning, match=msg):+            result = func(idx)+        assert result == func(np.array([1, 2, 4]))++    @pytest.mark.parametrize("func", [np.sum, np.prod])+    def test_numpy_reductions_categorical_raises(self, func):+        # GH#50021 numpy raised here before Index.sum/prod existed+        idx = pd.CategoricalIndex([1, 2, 4])+        with pytest.raises(TypeError, match="does not support operation"):+            func(idx)++    @pytest.mark.parametrize(+        "kwargs, expected",+        [+            ({"dtype": "float32"}, 3.0),+            ({"keepdims": True}, np.array([3.0])),+            ({"initial": 5}, 8.0),+        ],+    )+    def test_numpy_reductions_numpy_kwargs_deprecated(self, kwargs, expected):+        # GH#50021 the Index methods do not support these, like Series+        idx = pd.Index([1.0, 2.0])+        with tm.assert_produces_warning(Pandas4Warning, match="will call Index.sum"):+            result = np.sum(idx, **kwargs)+        tm.assert_almost_equal(result, expected)++    def test_ufunc_reduce_numpy_kwargs(self):+        # GH#50021 np.add.reduce keeps numpy's handling of dtype+        idx = pd.Index([1, 2])+        with tm.assert_produces_warning(None):+            result = np.add.reduce(idx, dtype="float32")+        assert result == 3.0+  class TestSeriesReductions:     # Note: the name TestSeriesReductions indicates these tests@@ -2056,6 +2188,28 @@ def test_any_all_python_scalars(     assert type(result) is expected  +@pytest.mark.parametrize("how", ["sum", "prod"])+@pytest.mark.parametrize(+    "dtype",+    [+        "float64",+        "Int64",+        pytest.param(+            "float64[pyarrow]",+            marks=pytest.mark.skipif(not HAS_PYARROW, reason="requires pyarrow"),+        ),+    ],+)+def test_negative_min_count_deprecated_index(how, dtype):+    # GH#50022+    idx = pd.Index([2, None, 3], dtype=dtype)+    expected = getattr(idx, how)(min_count=0)+    msg = "Passing a negative value for 'min_count' is deprecated"+    with tm.assert_produces_warning(Pandas4Warning, match=msg):+        result = getattr(idx, how)(min_count=-1)+    assert result == expected++ @pytest.mark.parametrize(     "dtype",     ["Int64", "Float64", "boolean", "Sparse[int64]", "Sparse[float64]", "Sparse[bool]"],