Created
May 31, 2021 12:32
-
-
Save AayushSameerShah/5c3958522082133dd4739e50c83d6223 to your computer and use it in GitHub Desktop.
This code snippet will show how to deal with the order of levels when you want to stack or unstack the df
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Examples can be found in Pandas Book (Notebooks) 3 Section > 2. Combining, Merging | |
# This is very manual (but a kind of hack) | |
df.stack(level= [0, 1]).unstack(level= [1, 2, 3]) | |
# Desired level and their order ↑ (Both stack / unstack required) | |
# Real Way - efficient | |
df.unstack().swaplevel(2, 0, axis= 1).sort_index(level= 0, aixs= 1) | |
# This is the ↑ person. ↑ This sorting is optional but required for cleaner dataset |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From here: https://stackoverflow.com/questions/29859296/how-do-i-change-order-grouping-level-of-pandas-multiindex-columns