Skip to content

Commit ea22f10

Browse files
bashtageKevin Sheppard
authored and
Kevin Sheppard
committed
BUG: Correct crosstabl for categorical inputs
Change catch types to reflect error changes closes #37465
1 parent 0647f02 commit ea22f10

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

doc/source/whatsnew/v1.1.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Fixed regressions
2929
- Fixed regression in :class:`StataReader` which required ``chunksize`` to be manually set when using an iterator to read a dataset (:issue:`37280`)
3030
- Fixed regression in setitem with :meth:`DataFrame.iloc` which raised error when trying to set a value while filtering with a boolean list (:issue:`36741`)
3131
- Fixed regression in :attr:`MultiIndex.is_monotonic_increasing` returning wrong results with ``NaN`` in at least one of the levels (:issue:`37220`)
32+
- Fixed regression in :meth:`crosstab` that failed when the input series are categorical. (:issue:`37465`)
3233

3334
.. ---------------------------------------------------------------------------
3435

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)