Skip to content

Instantly share code, notes, and snippets.

@Atlas7
Created February 5, 2018 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Atlas7/a926b770f7c9a735a75c80c4c1d2c3c5 to your computer and use it in GitHub Desktop.
Save Atlas7/a926b770f7c9a735a75c80c4c1d2c3c5 to your computer and use it in GitHub Desktop.
Pandas Multi Index Examples

Say I have a multi-index DataFrame that looks like this:

In [5]: sales
Out[5]: 
             eggs  salt  spam
state month                  
CA    1        47  12.0    17
      2       110  50.0    31
NY    1       221  89.0    72
      2        77  87.0    20
TX    1       132   NaN    52
      2       205  60.0    55

To select using multi index. Exmples:

# Look up data for NY in month 1: NY_month1
NY_month1 = sales.loc[(["NY"], [1]), :]

# Look up data for CA and TX in month 2: CA_TX_month2
CA_TX_month2 = sales.loc[(["CA", "TX"], [2]), :]

# Look up data for all states in month 2: all_month2
all_month2 = sales.loc[(slice(None), [2]), :]

Reference: DataCamp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment