Skip to content

BUG: DataFrame.stack with sort=True and unsorted MultiIndex levels #53636

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

Closed
rhshadrach opened this issue Jun 13, 2023 · 2 comments · Fixed by #53637
Closed

BUG: DataFrame.stack with sort=True and unsorted MultiIndex levels #53636

rhshadrach opened this issue Jun 13, 2023 · 2 comments · Fixed by #53637
Assignees
Labels
Bug Reshaping Concat, Merge/Join, Stack/Unstack, Explode

Comments

@rhshadrach
Copy link
Member

Ref: #53282 (comment)

levels = ((0, 1), (1, 0))
stack_lev = 1
columns = MultiIndex(levels=levels, codes=[[0, 0, 1, 1], [0, 1, 0, 1]])
df = DataFrame(columns=columns, data=[range(4)])
df_stacked = df.stack(stack_lev, sort=True)
#      0  1
# 0 1  0  2
#   0  1  3

# Expected
#      0  1
# 0 0  1  3
#   1  0  2

When the MultiIndex levels are not sorted in ascending order, DataFrame.stack with sort=True does not sort the values in the result.

@rhshadrach rhshadrach added Bug Reshaping Concat, Merge/Join, Stack/Unstack, Explode labels Jun 13, 2023
@rhshadrach rhshadrach self-assigned this Jun 13, 2023
@rhshadrach
Copy link
Member Author

rhshadrach commented Jun 21, 2023

This was a misunderstanding of what sort=True is supposed to do. When sort=True, the levels of the MultiIndex get sorted, but not the values. I plan to clarify the docs here.

@jorisvandenbossche
Copy link
Member

To be honest, I don't even really understand your last sentence ;)
What do you mean with the "levels get sorted"? Do you mean the labels of one level (eg df_stacked.index.levels[-1]), or the integer codes of the levels (df_stacked.index.codes[-1]) while keeping the labels the same?

The above example might also not be the best, because I don't see any difference between sort=True vs sort=False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug Reshaping Concat, Merge/Join, Stack/Unstack, Explode
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants