-
-
Notifications
You must be signed in to change notification settings - Fork 19.3k
Better error message on when the dataframe is empty for margins=True
#63133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
pandas/core/reshape/pivot.py
Outdated
|
|
||
| table_index = table.index | ||
| table_columns = table.columns | ||
| last_ind_or_col = table.iloc[-1, :].name |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
| last_ind_or_col = table.iloc[-1, :].name | ||
| except IndexError as err: | ||
| raise IndexError( | ||
| "Can't get margins since the result dataframe is empty" |
There was a problem hiding this comment.
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?"
For the issue #60768
In
crosstabfunction, if the result dataframe is empty andmargins=True, then we getindex-out-of-boundssince 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.doc/source/whatsnew/vX.X.X.rstfile if fixing a bug or adding a new feature.AGENTS.md.