pandas-dev/pandas · #72003

ENH: add numeric_only to GroupBy.ohlc and Resampler.ohlc (GH#56946)

jbrockmendel · merged Nov 12, 20266 files · 77 + / 6 −
doc/source/whatsnew/v3.2.0.rst1 + / 0 −
@@ -31,6 +31,7 @@ Other enhancements - :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`) - :func:`read_csv` with the ``"c"`` and ``"python"`` engines now accepts a :class:`DatetimeTZDtype` in ``dtype`` (:issue:`24542`)+- :meth:`.DataFrameGroupBy.ohlc`, :meth:`.SeriesGroupBy.ohlc` and :meth:`.Resampler.ohlc` now accept a ``numeric_only`` argument (:issue:`56946`) - :meth:`.DataFrameGroupBy.plot` now titles each group's figure with its group key, unless ``title`` or ``ax`` is passed (:issue:`12452`) - :meth:`.DataFrameGroupBy.rank` and :meth:`.SeriesGroupBy.rank` now accept a ``numeric_only`` argument, matching :meth:`DataFrame.rank` (:issue:`44438`) - :meth:`DataFrame.plot.area` and :meth:`Series.plot.area` now accept keyword arguments that only the lines or only the filled areas support, such as ``hatch``, ``edgecolor`` and ``marker``, instead of raising ``AttributeError``; ``hatch`` also accepts a list with one hatch per column (:issue:`12354`)
pandas/core/groupby/generic.py3 + / 1 −
@@ -3135,10 +3135,12 @@ def _get_data_to_aggregate(     def _wrap_agged_manager(self, mgr: BlockManager) -> DataFrame:         return self.obj._constructor_from_mgr(mgr, axes=mgr.axes) -    def _apply_to_column_groupbys(self, func) -> DataFrame:+    def _apply_to_column_groupbys(self, func, numeric_only: bool = False) -> DataFrame:         from pandas.core.reshape.concat import concat          obj = self._obj_with_exclusions+        if numeric_only:+            obj = obj._get_numeric_data()         columns = obj.columns         sgbs = (             SeriesGroupBy(
pandas/core/groupby/groupby.py16 + / 2 −
@@ -3397,12 +3397,19 @@ def last(x: Series):         )      @final-    def ohlc(self) -> DataFrame:+    def ohlc(self, numeric_only: bool = False) -> DataFrame:         """         Compute open, high, low and close values of a group, excluding missing values.          For multiple groupings, the result index will be a MultiIndex +        Parameters+        ----------+        numeric_only : bool, default False+            Include only float, int, boolean columns.++            .. versionadded:: 3.2.0+         Returns         -------         DataFrame@@ -3494,6 +3501,11 @@ def ohlc(self) -> DataFrame:             obj = self._selected_obj              is_numeric = is_numeric_dtype(obj.dtype)+            if numeric_only and not is_numeric:+                raise TypeError(+                    f"Cannot use numeric_only=True with {type(self).__name__}.ohlc "+                    "and non-numeric dtypes."+                )             if not is_numeric:                 raise DataError("No numeric types to aggregate") @@ -3509,7 +3521,9 @@ def ohlc(self) -> DataFrame:                 result = result.reset_index()             return result -        result = self._apply_to_column_groupbys(lambda sgb: sgb.ohlc())+        result = self._apply_to_column_groupbys(+            lambda sgb: sgb.ohlc(), numeric_only=numeric_only+        )         return result      def describe(
pandas/core/resample.py11 + / 2 −
@@ -1749,13 +1749,20 @@ def sem(         return self._downsample("sem", ddof=ddof, numeric_only=numeric_only)      @final-    def ohlc(self):+    def ohlc(self, numeric_only: bool = False):         """         Compute open, high, low and close values of a group, excluding missing values.          This method computes OHLC (Open-High-Low-Close) values, commonly used         in financial data analysis to summarize price movements within time periods. +        Parameters+        ----------+        numeric_only : bool, default False+            Include only float, int, boolean columns.++            .. versionadded:: 3.2.0+         Returns         -------         DataFrame@@ -1791,6 +1798,8 @@ def ohlc(self):         obj = self._obj_with_exclusions         if len(ax) == 0:             # GH#42902+            if numeric_only and obj.ndim == 2:+                obj = obj._get_numeric_data()             obj = obj.copy()             obj.index = _asfreq_compat(obj.index, self.freq)             if obj.ndim == 1:@@ -1803,7 +1812,7 @@ def ohlc(self):                 obj = obj.reindex(mi, axis=1)             return obj -        return self._downsample("ohlc")+        return self._downsample("ohlc", numeric_only=numeric_only)      @final     def nunique(self):
pandas/tests/groupby/test_numeric_only.py35 + / 1 −
@@ -3,7 +3,10 @@ import pytest  from pandas._libs import lib-from pandas.errors import Pandas4Warning+from pandas.errors import (+    DataError,+    Pandas4Warning,+)  import pandas as pd import pandas._testing as tm@@ -429,3 +432,34 @@ def test_deprecate_numeric_only_series(dtype, groupby_func, request):         result = method(*args, numeric_only=True)         expected = method(*args, numeric_only=False)         tm.assert_series_equal(result, expected)+++@pytest.mark.parametrize("as_index", [True, False])+def test_ohlc_numeric_only(as_index):+    # GH#56946+    df = pd.DataFrame(+        {+            "key": [1, 1, 2, 2],+            "str": list("abcd"),+            "num": [1.0, 3.0, 2.0, 5.0],+            "dt": pd.date_range("2020", periods=4),+            "flag": [True, False, True, False],+        }+    )+    gb = df.groupby("key", as_index=as_index)++    with pytest.raises(DataError, match="No numeric types to aggregate"):+        gb.ohlc()++    result = gb.ohlc(numeric_only=True)+    expected = gb[["num", "flag"]].ohlc()+    tm.assert_frame_equal(result, expected)+++def test_ohlc_numeric_only_series_raises():+    # GH#56946+    ser = pd.Series(list("abcd"))+    gb = ser.groupby([1, 1, 2, 2])+    msg = "Cannot use numeric_only=True with SeriesGroupBy.ohlc and non-numeric dtypes"+    with pytest.raises(TypeError, match=msg):+        gb.ohlc(numeric_only=True)
pandas/tests/resample/test_resample_api.py11 + / 0 −
@@ -1156,3 +1156,14 @@ def test_asfreq_respects_origin_with_fixed_freq_all_seconds_equal():      exp = pd.DataFrame({"value": [np.nan, np.nan, np.nan]}, index=exp_idx)     tm.assert_frame_equal(result, exp)+++@pytest.mark.parametrize("periods", [4, 0])+def test_resample_ohlc_numeric_only(periods):+    # GH#56946+    index = date_range("2020-01-01", periods=4, freq="12h")+    df = pd.DataFrame({"str": list("abcd"), "num": [1.0, 3.0, 2.0, 5.0]}, index=index)+    df = df.iloc[:periods]+    result = df.resample("D").ohlc(numeric_only=True)+    expected = df[["num"]].resample("D").ohlc()+    tm.assert_frame_equal(result, expected)