Skip to content

BUG: Fix issue where df.groupby.resample.size returns wide DF instead of MultiIndex Series. #50440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/resample/test_resampler_grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)