1

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 4

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

I feel drop is better ~ :-)
3

This should work as well:

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

Comments

2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.