Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,9 +1163,15 @@ def _normalize(

elif margins is True:
# keep index and column of pivoted table

table_index = table.index
table_columns = table.columns
last_ind_or_col = table.iloc[-1, :].name
try:
last_ind_or_col = table.iloc[-1, :].name
except IndexError as err:
raise IndexError(
"Can't get margins since the result dataframe is empty"
) from err

# check if margin name is not in (for MI cases) and not equal to last
# index/column and save the column and index margin
Expand Down
35 changes: 35 additions & 0 deletions pandas/tests/reshape/test_crosstab.py
Original file line number Diff line number Diff line change
Expand Up @@ -877,3 +877,38 @@ 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_empty_result_with_normalize():
# https://github.com/pandas-dev/pandas/issues/60768
index = ["index1", "index2", "index3"]
columns = ["col1", "col2", "col3"]
values = [1, 2, 3]

with pytest.raises(IndexError, match="Can't get margins"):
# Raise error when margins=True
crosstab(
index,
columns,
values=values,
normalize=1,
margins=True,
dropna=True,
aggfunc="skew",
)

# No error when margins=False, just return empty DataFrame
result = crosstab(
index,
columns,
values=values,
normalize=1,
margins=False,
dropna=True,
aggfunc="skew",
)
expected = DataFrame(
index=Index([], dtype="str", name="row_0"),
columns=Index([], dtype="str", name="col_0"),
)
tm.assert_frame_equal(result, expected)
Loading