Skip to content

Instantly share code, notes, and snippets.

@xvrdm
Last active December 15, 2015 16:40
Show Gist options
  • Save xvrdm/2382ecd498e58d812a5e to your computer and use it in GitHub Desktop.
Save xvrdm/2382ecd498e58d812a5e to your computer and use it in GitHub Desktop.
Pivot and Stack in Python using Pandas

Process:

  1. Index all columns that don't need reshape
  2. Stack the rest
df
first second         A         B
bar   one     0.721555 -0.706771
bar   two    -1.039575  0.271860
baz   one    -0.424972  0.567020
baz   two     0.276232 -1.087401

# Choosing index columns by name
df = df.set_index(['first','second']) 

# Choosing index columns by df.columns filtering
# (here all columns before the column named "January")
df = df.set_index(df.columns.tolist()[:df.columns.tolist().index('A')]) 

df
                     A         B
first second                    
bar   one     0.721555 -0.706771
      two    -1.039575  0.271860
baz   one    -0.424972  0.567020
      two     0.276232 -1.087401

# Stack all non-index columns and reset index
df = df.stack()

df
first  second   
bar    one     A    0.721555
               B   -0.706771
       two     A   -1.039575
               B    0.271860
baz    one     A   -0.424972
               B    0.567020
       two     A    0.276232
               B   -1.087401

# Reset indexes to go back to flat structure
df = df.reset_index()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment