diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 13b60f7f05352..59a27b0969a1e 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -951,6 +951,7 @@ Groupby/resample/rolling - Bug in :meth:`.SeriesGroupBy.nth` would raise when grouper contained NA values after subsetting from a :class:`DataFrameGroupBy` (:issue:`26454`) - Bug in :meth:`DataFrame.groupby` would not include a :class:`.Grouper` specified by ``key`` in the result when ``as_index=False`` (:issue:`50413`) - Bug in :meth:`.DataFrameGrouBy.value_counts` would raise when used with a :class:`.TimeGrouper` (:issue:`50486`) +- Bug in :meth:`Resampler.size` caused a wide :class:`DataFrame` to be returned instead of a :class:`Series` with :class:`MultiIndex` (:issue:`46826`) - Reshaping diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 4af4be20a056e..d6cba824767b5 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -989,6 +989,12 @@ def var( @doc(GroupBy.size) def size(self): result = self._downsample("size") + + # If the result is a non-empty DataFrame we stack to get a Series + # GH 46826 + if isinstance(result, ABCDataFrame) and not result.empty: + result = result.stack() + if not len(self.ax): from pandas import Series diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index 0432cf397067d..a521e24aa6022 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -515,3 +515,25 @@ def test_resample_empty_Dataframe(keys): expected.index.name = keys[0] tm.assert_frame_equal(result, expected) + + +def test_groupby_resample_size_all_index_same(): + # GH 46826 + df = DataFrame( + {"A": [1] * 3 + [2] * 3 + [1] * 3 + [2] * 3, "B": np.arange(12)}, + index=date_range("31/12/2000 18:00", freq="H", periods=12), + ) + result = df.groupby("A").resample("D").size() + expected = Series( + 3, + index=pd.MultiIndex.from_tuples( + [ + (1, Timestamp("2000-12-31")), + (1, Timestamp("2001-01-01")), + (2, Timestamp("2000-12-31")), + (2, Timestamp("2001-01-01")), + ], + names=["A", None], + ), + ) + tm.assert_series_equal(result, expected)