Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AayushSameerShah/5c3958522082133dd4739e50c83d6223 to your computer and use it in GitHub Desktop.
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
# 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