Skip to content

BUG: Correct crosstab for categorical inputs #37468

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 1 commit into from
Oct 31, 2020
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
3 changes: 1 addition & 2 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,8 +329,7 @@ def _all_key(key):
piece = piece.copy()
try:
piece[all_key] = margin[key]
except TypeError:

except ValueError:
# we cannot reshape, so coerce the axis
piece.set_axis(
piece._get_axis(cat_axis)._to_safe_for_reshape(),
Expand Down
32 changes: 32 additions & 0 deletions pandas/tests/reshape/test_crosstab.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import numpy as np
import pytest

from pandas.core.dtypes.common import is_categorical_dtype

from pandas import CategoricalIndex, DataFrame, Index, MultiIndex, Series, crosstab
import pandas._testing as tm

Expand Down Expand Up @@ -743,3 +745,33 @@ def test_margin_normalize_multiple_columns(self):
)
expected.index.name = "C"
tm.assert_frame_equal(result, expected)


@pytest.mark.parametrize("a_dtype", ["category", "int64"])
@pytest.mark.parametrize("b_dtype", ["category", "int64"])
def test_categoricals(a_dtype, b_dtype):
# https://github.com/pandas-dev/pandas/issues/37465
g = np.random.RandomState(25982704)
Copy link
Contributor

Choose a reason for hiding this comment

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

it might be worth parameterize this to check if a is a cat and b is not (and vice versa), might be slightly tricky.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

These have been parameterized. I'll ping on green.

a = Series(g.randint(0, 3, size=100)).astype(a_dtype)
b = Series(g.randint(0, 2, size=100)).astype(b_dtype)
result = crosstab(a, b, margins=True, dropna=False)
columns = Index([0, 1, "All"], dtype="object", name="col_0")
index = Index([0, 1, 2, "All"], dtype="object", name="row_0")
values = [[18, 16, 34], [18, 16, 34], [16, 16, 32], [52, 48, 100]]
expected = DataFrame(values, index, columns)
tm.assert_frame_equal(result, expected)

# Verify when categorical does not have all values present
a.loc[a == 1] = 2
a_is_cat = is_categorical_dtype(a.dtype)
assert not a_is_cat or a.value_counts().loc[1] == 0
result = crosstab(a, b, margins=True, dropna=False)
values = [[18, 16, 34], [0, 0, np.nan], [34, 32, 66], [52, 48, 100]]
Copy link
Member

Choose a reason for hiding this comment

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

@bashtage im working on a branch that is failing on this test, getting a 0 instead of an nan here. is there any chance the branch is right and the test is wrong?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think it is quite likley that it should be 0.0. The NaN is in the margins column, which is normalized. Not totally sure how `NaN crept in.

expected = DataFrame(values, index, columns)
if not a_is_cat:
expected = expected.loc[[0, 2, "All"]]
expected["All"] = expected["All"].astype("int64")
print(result)
print(expected)
print(expected.loc[[0, 2, "All"]])
tm.assert_frame_equal(result, expected)