diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index cfc6f91557781..0762f11028c8f 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -1144,6 +1144,10 @@ def _normalize( # keep index and column of pivoted table table_index = table.index table_columns = table.columns + + if table.empty: + return table + last_ind_or_col = table.iloc[-1, :].name # check if margin name is not in (for MI cases) and not equal to last diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 070c756e8c928..49cec94a518e7 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -877,3 +877,17 @@ def test_categoricals(a_dtype, b_dtype): expected = expected.loc[[0, 2, "All"]] expected["All"] = expected["All"].astype("int64") tm.assert_frame_equal(result, expected) + +def test_crosstab_aggfunc_skew(): + # Test case for crosstab with aggfunc='skew' + result = crosstab( + index=["index1", "index2"], + columns=["one", "one"], + values=[12, 10], + normalize=1, + margins=True, + dropna=True, + aggfunc='skew' + ) + assert isinstance(result, DataFrame) + assert not result.empty