Skip to content

Commit b15f90f

Browse files
committed
BUG: Correct crosstabl for categorical inputs
Change catch types to reflect error changes closes #37465
1 parent d89331b commit b15f90f

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

pandas/core/reshape/pivot.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -329,8 +329,7 @@ def _all_key(key):
329329
piece = piece.copy()
330330
try:
331331
piece[all_key] = margin[key]
332-
except TypeError:
333-
332+
except (TypeError, ValueError):
334333
# we cannot reshape, so coerce the axis
335334
piece.set_axis(
336335
piece._get_axis(cat_axis)._to_safe_for_reshape(),

pandas/tests/reshape/test_crosstab.py

+12
Original file line numberDiff line numberDiff line change
@@ -743,3 +743,15 @@ def test_margin_normalize_multiple_columns(self):
743743
)
744744
expected.index.name = "C"
745745
tm.assert_frame_equal(result, expected)
746+
747+
748+
def test_categoricals():
749+
g = np.random.RandomState(25982704)
750+
a = Series(g.randint(0, 3, size=100)).astype("category")
751+
b = Series(g.randint(0, 2, size=100)).astype("category")
752+
result = crosstab(a, b, margins=True, dropna=False)
753+
columns = Index([0, 1, "All"], dtype="object", name="col_0")
754+
index = Index([0, 1, 2, "All"], dtype="object", name="row_0")
755+
values = [[18, 16, 34], [18, 16, 34], [16, 16, 32], [52, 48, 100]]
756+
expected = DataFrame(values, index, columns)
757+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)