Skip to content

Commit 105ffeb

Browse files
Fix crosstab(aggfunc='skew') bug
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`.
1 parent 0a1577f commit 105ffeb

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

pandas/core/reshape/pivot.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1144,6 +1144,10 @@ def _normalize(
11441144
# keep index and column of pivoted table
11451145
table_index = table.index
11461146
table_columns = table.columns
1147+
1148+
if table.empty:
1149+
return table
1150+
11471151
last_ind_or_col = table.iloc[-1, :].name
11481152

11491153
# check if margin name is not in (for MI cases) and not equal to last

pandas/tests/reshape/test_crosstab.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,3 +877,17 @@ def test_categoricals(a_dtype, b_dtype):
877877
expected = expected.loc[[0, 2, "All"]]
878878
expected["All"] = expected["All"].astype("int64")
879879
tm.assert_frame_equal(result, expected)
880+
881+
def test_crosstab_aggfunc_skew():
882+
# Test case for crosstab with aggfunc='skew'
883+
result = crosstab(
884+
index=["index1", "index2"],
885+
columns=["one", "one"],
886+
values=[12, 10],
887+
normalize=1,
888+
margins=True,
889+
dropna=True,
890+
aggfunc='skew'
891+
)
892+
assert isinstance(result, DataFrame)
893+
assert not result.empty

0 commit comments

Comments
 (0)