diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 7fc856be374e9..a8afcdfc98c94 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1367,6 +1367,7 @@ Groupby/resample/rolling - Bug in :meth:`.DataFrameGroupBy.describe` produced incorrect results when data had duplicate columns (:issue:`50806`) - Bug in :meth:`.DataFrameGroupBy.agg` with ``engine="numba"`` failing to respect ``as_index=False`` (:issue:`51228`) - Bug in :meth:`DataFrameGroupBy.agg`, :meth:`SeriesGroupBy.agg`, and :meth:`Resampler.agg` would ignore arguments when passed a list of functions (:issue:`50863`) +- Bug in :meth:`DataFrameGroupBy.ohlc` ignoring ``as_index=False`` (:issue:`51413`) - Reshaping diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 8dcf7a0838349..5ccf7323d8a3a 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2501,10 +2501,13 @@ def ohlc(self) -> DataFrame: ) return self._reindex_output(result) - # TODO: 2023-02-05 all tests that get here have self.as_index - return self._apply_to_column_groupbys( + result = self._apply_to_column_groupbys( lambda x: x.ohlc(), self._obj_with_exclusions ) + if not self.as_index: + result = self._insert_inaxis_grouper(result) + result.index = default_index(len(result)) + return result @doc(DataFrame.describe) def describe( diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 4872cc27cde9a..6c591616e8469 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -586,7 +586,8 @@ def test_ohlc_ea_dtypes(any_numeric_ea_dtype): {"a": [1, 1, 2, 3, 4, 4], "b": [22, 11, pd.NA, 10, 20, pd.NA]}, dtype=any_numeric_ea_dtype, ) - result = df.groupby("a").ohlc() + gb = df.groupby("a") + result = gb.ohlc() expected = DataFrame( [[22, 22, 11, 11], [pd.NA] * 4, [10] * 4, [20] * 4], columns=MultiIndex.from_product([["b"], ["open", "high", "low", "close"]]), @@ -595,6 +596,11 @@ def test_ohlc_ea_dtypes(any_numeric_ea_dtype): ) tm.assert_frame_equal(result, expected) + gb2 = df.groupby("a", as_index=False) + result2 = gb2.ohlc() + expected2 = expected.reset_index() + tm.assert_frame_equal(result2, expected2) + @pytest.mark.parametrize("dtype", [np.int64, np.uint64]) @pytest.mark.parametrize("how", ["first", "last", "min", "max", "mean", "median"])