drop a level two column from multi index dataframe

Viewed 76

Consider this dataframe:

import pandas as pd
import numpy as np
iterables = [['bar', 'baz', 'foo'], ['one', 'two']]
index = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(3, 6), index=['A', 'B', 'C'], columns=index)
print(df)
first        bar                 baz                 foo          
second       one       two       one       two       one       two
A      -1.954583 -1.347156 -1.117026 -1.253150  0.057197 -1.520180
B       0.253937  1.267758 -0.805287  0.337042  0.650892 -0.379811
C       0.354798 -0.835234  1.172324 -0.663353  1.145299  0.651343

I would like to drop 'one' from each column, while retaining other structure.
With the end result looking something like this:

first        bar       baz       foo          
second       two       two       two
A      -1.347156 -1.253150 -1.520180
B       1.267758  0.337042 -0.379811
C      -0.835234 -0.663353  0.651343
4 Answers

Use drop:

df.drop('one', axis=1, level=1)
first        bar       baz       foo
second       two       two       two
A       0.127419 -0.319655 -0.878161
B      -0.563335  1.193819 -0.469539
C      -1.324932 -0.550495  1.378335

This should work as well:

df.loc[:,df.columns.get_level_values(1)!='one']

Try:

print(df.loc[:, (slice(None), "two")])

Prints:

first        bar       baz       foo
second       two       two       two
A      -1.104831  0.286379  1.121148
B      -1.637677 -2.297138  0.381137
C      -1.556391  0.779042  2.316628

Use pd.IndexSlice:

indx = pd.IndexSlice
df.loc[:, indx[:, 'two']]

Output:

first        bar       baz       foo
second       two       two       two
A       1.169699  1.434761  0.917152
B      -0.732991 -0.086613 -0.803092
C      -0.813872 -0.706504  0.227000
Related