Skip to content

BUG: SeriesGroupBy.value_counts - index name missing in categorical columns #45625

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 12 commits into from
Feb 5, 2022
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/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ Datetimelike
- Bug in :func:`to_datetime` with sequences of ``np.str_`` objects incorrectly raising (:issue:`32264`)
- Bug in :class:`Timestamp` construction when passing datetime components as positional arguments and ``tzinfo`` as a keyword argument incorrectly raising (:issue:`31929`)
- Bug in :meth:`Index.astype` when casting from object dtype to ``timedelta64[ns]`` dtype incorrectly casting ``np.datetime64("NaT")`` values to ``np.timedelta64("NaT")`` instead of raising (:issue:`45722`)
- Bug in :meth:`SeriesGroupBy.value_counts` index when passing categorical column (:issue:`44324`)
-

Timedelta
Expand Down
23 changes: 11 additions & 12 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,23 +602,23 @@ def value_counts(
ids, _, _ = self.grouper.group_info
val = self.obj._values

def apply_series_value_counts():
return self.apply(
Copy link
Member

Choose a reason for hiding this comment

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

Could you take this opportunity to refactor and inline this logic like

if (bins is not None and np.iterable(bins) or is_categorical_dtype(val.dtype):
    # comments
    s = self.apply(...)
    s.index.names = ...

Also will s always have a MultiIndex here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

If I run the test code with the following change

    if is_categorical_dtype(val.dtype) or (bins and np.iterable(bins)):
        # scalar bins cannot be done at top level
        # in a backward compatible way
        # GH38672
        s = self.apply(
            Series.value_counts,
            normalize=normalize,
            sort=sort,
            ascending=ascending,
            bins=bins,
        )
        print(s.index)
        s.index.names = names

I get these results

df = pd.DataFrame(
    {
        "gender": ["female"],
        "country": ["US"],
    }
)
df["gender"] = df["gender"].astype("category")
result2 = df.groupby("country")["gender"].value_counts()
MultiIndex([('US', 'female')],
           names=['country', None])

And I think the fact that we are inside a group by should always ensure that we are always using MultiIndex.

Running the following code calls a different method. Specifically, pandas.core.algorithms.value_counts.

names = self.grouper.names + [self.obj.name]

if is_categorical_dtype(val.dtype) or (
bins is not None and not np.iterable(bins)
):
# scalar bins cannot be done at top level
# in a backward compatible way
# GH38672 relates to categorical dtype
ser = self.apply(
Series.value_counts,
normalize=normalize,
sort=sort,
ascending=ascending,
bins=bins,
)

if bins is not None:
if not np.iterable(bins):
# scalar bins cannot be done at top level
# in a backward compatible way
return apply_series_value_counts()
elif is_categorical_dtype(val.dtype):
# GH38672
return apply_series_value_counts()
ser.index.names = names
return ser

# groupby removes null keys from groupings
mask = ids != -1
Expand Down Expand Up @@ -683,7 +683,6 @@ def apply_series_value_counts():
levels = [ping.group_index for ping in self.grouper.groupings] + [
lev # type: ignore[list-item]
]
names = self.grouper.names + [self.obj.name]

if dropna:
mask = codes[-1] != -1
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/groupby/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def test_sorting_with_different_categoricals():
index = ["low", "med", "high", "low", "med", "high"]
index = Categorical(index, categories=["low", "med", "high"], ordered=True)
index = [["A", "A", "A", "B", "B", "B"], CategoricalIndex(index)]
index = MultiIndex.from_arrays(index, names=["group", None])
index = MultiIndex.from_arrays(index, names=["group", "dose"])
expected = Series([2] * 6, index=index, name="dose")
tm.assert_series_equal(result, expected)

Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/groupby/test_value_counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,26 @@
import pandas._testing as tm


def tests_value_counts_index_names_category_column():
# GH44324 Missing name of index category column
df = DataFrame(
{
"gender": ["female"],
"country": ["US"],
}
)
df["gender"] = df["gender"].astype("category")
result = df.groupby("country")["gender"].value_counts()

# Construct expected, very specific multiindex
df_mi_expected = DataFrame([["US", "female"]], columns=["country", "gender"])
df_mi_expected["gender"] = df_mi_expected["gender"].astype("category")
mi_expected = MultiIndex.from_frame(df_mi_expected)
expected = Series([1], index=mi_expected, name="gender")

tm.assert_series_equal(result, expected)


# our starting frame
def seed_df(seed_nans, n, m):
np.random.seed(1234)
Expand Down