Skip to content
Open
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
3 changes: 3 additions & 0 deletions pandas/core/reshape/pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,6 +1163,9 @@ def _normalize(

elif margins is True:
# keep index and column of pivoted table
if table.empty:
raise ValueError("Can't get margins since the result dataframe is empty")

table_index = table.index
table_columns = table.columns
last_ind_or_col = table.iloc[-1, :].name
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for improving the error message.
I suggest leaving the error type IndexError as it is and re-raising with a different error message.

We can put this line table.iloc[-1, :].name, where we get the problem with indexing, in a try block and then re-raise:

except IndexError as err:
    raise IndexError("Can't get margins since the result dataframe is empty") from err

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@show981111, could you please add a test for the new error message?

Expand Down
Loading