Skip to content

BUG: value_counts can handle the case even with empty groups (#28479) #28607

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

Closed
wants to merge 2 commits into from
Closed
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/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ Other
- Using :meth:`DataFrame.replace` with overlapping keys in a nested dictionary will no longer raise, now matching the behavior of a flat dictionary (:issue:`27660`)
- :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now support dicts as ``compression`` argument with key ``'method'`` being the compression method and others as additional compression options when the compression method is ``'zip'``. (:issue:`26023`)
- :meth:`Series.append` will no longer raise a ``TypeError`` when passed a tuple of ``Series`` (:issue:`28410`)
- :meth:`SeriesGroupBy.value_counts` will be able to handle the case even when the :class:`Grouper` makes empty groups (:issue: 28479)

.. _whatsnew_1000.contributors:

Expand Down
9 changes: 8 additions & 1 deletion pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,7 +1259,14 @@ def value_counts(
rep = partial(np.repeat, repeats=np.add.reduceat(inc, idx))

# multi-index components
labels = list(map(rep, self.grouper.recons_labels)) + [llab(lab, inc)]
try:
labels = list(map(rep, self.grouper.recons_labels)) + [llab(lab, inc)]
except ValueError:
# If applying rep to recons_labels go fail, use ids which has no
# consecutive duplicates instead.
_ids_idx = np.ones(len(ids), dtype=bool)
_ids_idx[1:] = ids[1:] != ids[:-1]
labels = list(map(rep, [ids[_ids_idx]])) + [llab(lab, inc)]
levels = [ping.group_index for ping in self.grouper.groupings] + [lev]
names = self.grouper.names + [self._selection_name]

Expand Down
27 changes: 26 additions & 1 deletion pandas/tests/groupby/test_value_counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import numpy as np
import pytest

from pandas import DataFrame, MultiIndex, Series, date_range
from pandas import DataFrame, MultiIndex, Series, date_range, Grouper
from pandas.util import testing as tm


Expand Down Expand Up @@ -79,3 +79,28 @@ def rebuild_index(df):
# have to sort on index because of unstable sort on values
left, right = map(rebuild_index, (left, right)) # xref GH9212
tm.assert_series_equal(left.sort_index(), right.sort_index())

@pytest.mark.parametrize(
"freq, size, frac", product(["1D", "2D", "1W", "1Y"], [100, 1000], [0.1, 0.5, 1])
)
def test_series_groupby_value_counts_with_grouper(freq, size, frac):
np.random.seed(42)

df = DataFrame.from_dict(
{
"date": date_range("2019-09-25", periods=size),
"name": np.random.choice(list("abcd"), size),
}
).sample(frac=frac)

gr = df.groupby(Grouper(key="date", freq=freq))["name"]

# have to sort on index because of unstable sort on values xref GH9212
result = gr.value_counts().sort_index()
expected = gr.apply(Series.value_counts).sort_index()
expected.index.names = (
result.index.names
) # .apply(Series.value_counts) can't create all names

tm.assert_series_equal(result, expected)