From 105ffeb58de732200814f395dfda11ee08eec93b Mon Sep 17 00:00:00 2001 From: Vishnu Sai Teja <112572028+Vishnu-sai-teja@users.noreply.github.com> Date: Sat, 8 Feb 2025 11:48:32 +0530 Subject: [PATCH] Fix crosstab(aggfunc='skew') bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix `IndexError` in `crosstab` with `aggfunc=‘skew’`. * Check if table is empty before accessing last row in `_normalize` function in `pandas/core/reshape/pivot.py`. * Skip normalization and return empty table if it is. * Add test case in `pandas/tests/reshape/test_crosstab.py` for `aggfunc=‘skew’`. * Ensure test case doesn’t raise `IndexError`. --- pandas/core/reshape/pivot.py | 4 ++++ pandas/tests/reshape/test_crosstab.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+) 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