Skip to content

BUG: groupby with categorical index doesn't include unobserved categories #49354

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
rhshadrach opened this issue Oct 27, 2022 · 0 comments · Fixed by #49373
Closed

BUG: groupby with categorical index doesn't include unobserved categories #49354

rhshadrach opened this issue Oct 27, 2022 · 0 comments · Fixed by #49373
Assignees
Labels
Bug Categorical Categorical Data Type Groupby

Comments

@rhshadrach
Copy link
Member

When a grouping by a CategoricalIndex, unobserved categories are not included in the output.

df = pd.DataFrame(
    {
        "a": pd.Categorical([1, 1, 2], categories=[1, 2, 3]),
        "a2": pd.Categorical([1, 1, 2], categories=[1, 2, 3]),
        "b": [4, 5, 6],
        "c": [7, 8, 9],
    }
).set_index(["a"])
gb = df.groupby("a", observed=False)
result = gb.sum()
print(result)
# Should include a row with 3, the unobserved category
#    b   c
# a       
# 1  9  15
# 2  6   9

df = df.reset_index().set_index(["a", "a2"])
gb = df.groupby(["a", "a2"], observed=False)
result = gb.sum()
print(result)
# Should include two rows with 3, the unobserved category
#       b   c
# a a2       
# 1 1   9  15
#   2   0   0
# 2 1   0   0
#   2   6   9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Categorical Categorical Data Type Groupby
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant