Skip to content

TST: added test for missing categories for value_counts #54837

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 8 commits into from
Aug 31, 2023
16 changes: 16 additions & 0 deletions pandas/tests/frame/methods/test_value_counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,19 @@ def test_value_counts_categorical_future_warning():
name="count",
)
tm.assert_series_equal(result, expected)


def test_value_counts_with_missing_category():
# GH-54836
df = pd.DataFrame({"a": pd.Categorical([1, 2, 4], categories=[1, 2, 3, 4])})
result = df.value_counts()
expected = pd.Series(
1,
index=pd.MultiIndex.from_arrays(
[pd.CategoricalIndex([1, 2, 4], categories=[1, 2, 3, 4], name="a")]
),
name="count",
)
# result should include the missing category
expected[3] = 0
Copy link
Member

Choose a reason for hiding this comment

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

Instead of modifying expected in the last line, it is slightly simpler to specify the correct results up front.

    expected = pd.Series(
        [1, 1, 1, 0],
        index=pd.MultiIndex.from_arrays(
            [pd.CategoricalIndex([1, 2, 4, 3], categories=[1, 2, 3, 4], name="a")]
        ),
        name="count",
    )

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion @rhshadrach . I have made the change.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@rhshadrach can you please take a look?

tm.assert_series_equal(result, expected)