Skip to content

Commit 6b10bb8

Browse files
authored
BUG: Fix issue where df.groupby.resample.size returns wide DF instead of MultiIndex Series. (#50440)
* Issue where df.groupby.resample.size returns DF. * Expected result is manually constructed. * Moved whatsnew entry to v2.0.0.rst.
1 parent c6d0bc0 commit 6b10bb8

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

doc/source/whatsnew/v2.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -952,6 +952,7 @@ Groupby/resample/rolling
952952
- Bug in :meth:`.SeriesGroupBy.nth` would raise when grouper contained NA values after subsetting from a :class:`DataFrameGroupBy` (:issue:`26454`)
953953
- Bug in :meth:`DataFrame.groupby` would not include a :class:`.Grouper` specified by ``key`` in the result when ``as_index=False`` (:issue:`50413`)
954954
- Bug in :meth:`.DataFrameGrouBy.value_counts` would raise when used with a :class:`.TimeGrouper` (:issue:`50486`)
955+
- Bug in :meth:`Resampler.size` caused a wide :class:`DataFrame` to be returned instead of a :class:`Series` with :class:`MultiIndex` (:issue:`46826`)
955956
-
956957

957958
Reshaping

pandas/core/resample.py

+6
Original file line numberDiff line numberDiff line change
@@ -989,6 +989,12 @@ def var(
989989
@doc(GroupBy.size)
990990
def size(self):
991991
result = self._downsample("size")
992+
993+
# If the result is a non-empty DataFrame we stack to get a Series
994+
# GH 46826
995+
if isinstance(result, ABCDataFrame) and not result.empty:
996+
result = result.stack()
997+
992998
if not len(self.ax):
993999
from pandas import Series
9941000

pandas/tests/resample/test_resampler_grouper.py

+22
Original file line numberDiff line numberDiff line change
@@ -515,3 +515,25 @@ def test_resample_empty_Dataframe(keys):
515515
expected.index.name = keys[0]
516516

517517
tm.assert_frame_equal(result, expected)
518+
519+
520+
def test_groupby_resample_size_all_index_same():
521+
# GH 46826
522+
df = DataFrame(
523+
{"A": [1] * 3 + [2] * 3 + [1] * 3 + [2] * 3, "B": np.arange(12)},
524+
index=date_range("31/12/2000 18:00", freq="H", periods=12),
525+
)
526+
result = df.groupby("A").resample("D").size()
527+
expected = Series(
528+
3,
529+
index=pd.MultiIndex.from_tuples(
530+
[
531+
(1, Timestamp("2000-12-31")),
532+
(1, Timestamp("2001-01-01")),
533+
(2, Timestamp("2000-12-31")),
534+
(2, Timestamp("2001-01-01")),
535+
],
536+
names=["A", None],
537+
),
538+
)
539+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)