Skip to content

ENH: Support observed keyword argument in Categorical.value_counts #44002

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
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ Other enhancements
- :meth:`.GroupBy.mean` now supports `Numba <http://numba.pydata.org/>`_ execution with the ``engine`` keyword (:issue:`43731`)
- :meth:`Timestamp.isoformat`, now handles the ``timespec`` argument from the base :class:``datetime`` class (:issue:`26131`)
- :meth:`NaT.to_numpy` ``dtype`` argument is now respected, so ``np.timedelta64`` can be returned (:issue:`44460`)
-
- :meth:`Categorical.value_counts` now supports the argument ``observed`` (:issue:`43498`)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you move to 1.5


.. ---------------------------------------------------------------------------

Expand Down
8 changes: 6 additions & 2 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -1602,7 +1602,7 @@ def notna(self) -> np.ndarray:

notnull = notna

def value_counts(self, dropna: bool = True):
def value_counts(self, dropna: bool = True, observed: bool = False):
"""
Return a Series containing counts of each category.

Expand All @@ -1612,6 +1612,9 @@ def value_counts(self, dropna: bool = True):
----------
dropna : bool, default True
Don't include counts of NaN.
observed : bool, default False
If True, only include counts for observed categories.
If False, include counts for all categories.

Returns
-------
Expand Down Expand Up @@ -1640,7 +1643,8 @@ def value_counts(self, dropna: bool = True):
ix = coerce_indexer_dtype(ix, self.dtype.categories)
ix = self._from_backing_data(ix)

return Series(count, index=CategoricalIndex(ix), dtype="int64")
counts = Series(count, index=CategoricalIndex(ix), dtype="int64")
return counts[counts != 0] if observed else counts

# error: Argument 2 of "_empty" is incompatible with supertype
# "NDArrayBackedExtensionArray"; supertype defines the argument type as
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/extension/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,17 @@ class TestMethods(base.BaseMethodsTests):
def test_value_counts(self, all_data, dropna):
return super().test_value_counts(all_data, dropna)

def test_value_counts_observed(self, data):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a ref to the GH issue similar to other tests

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

# GH 43498
# When observed=True is passed, unobserved categories should be omitted
data = data.add_categories(["#", "?"]) # Add some unobserved categories
series = pd.Series(data, dtype=data.categories.dtype)
result = data.value_counts(observed=True).sort_index()
expected = series.value_counts().sort_index()
self.assert_series_equal(
result, expected, check_index_type=False, check_categorical=False
)

def test_combine_add(self, data_repeated):
# GH 20825
# When adding categoricals in combine, result is a string
Expand Down