Skip to content

Conversation

@show981111
Copy link

For the issue #60768

In crosstab function, if the result dataframe is empty and margins=True, then we get index-out-of-bounds since the dataframe is empty. Instead of this, we can throw an error message indicating the result dataframe is empty so that the user can have a better idea.


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?

Copy link
Author

Choose a reason for hiding this comment

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

@natmokval Thank you for the feedback! I updated my code.

@natmokval natmokval added the Reshaping Concat, Merge/Join, Stack/Unstack, Explode label Nov 18, 2025
@show981111 show981111 requested a review from natmokval November 23, 2025 04:17
last_ind_or_col = table.iloc[-1, :].name
except IndexError as err:
raise IndexError(
"Can't get margins since the result dataframe is empty"
Copy link
Member

Choose a reason for hiding this comment

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

It's not clear to me that this is an improvement in the error message. For example with the OP of the linked issue, isn't a natural question a user would have is "Why is the result DataFrame empty?"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Reshaping Concat, Merge/Join, Stack/Unstack, Explode

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: crosstab(aggfunc='skew') raises IndexError: single positional indexer is out-of-bounds

3 participants