6

I have a df with multiple headers :

multicol = pd.MultiIndex.from_tuples([('France', '2017'), ('France', '2018'),('UK', '2017'), ('UK', '2018')], names = ("Country", "Year"))
df = pd.DataFrame([[1, 2, 5, 8], [2, 4, 2, 9]], index=['Number', 'Volume'], columns=multicol)

I want to print only the column France for 2018.

How can I do that ?

1 Answer 1

5

Use tuple for select columns in MultiIndex:

df = df[('France','2018')]
print (df)
Number    2
Volume    4
Name: (France, 2018), dtype: int64

For more complicated selects use slicers:

idx = pd.IndexSlice
a = df.loc['Number', idx['France','2018']]
print (a)
2

b = df.loc['Number', idx[:,'2018']]
print (b)
Country  Year
France   2018    2
UK       2018    8
Name: Number, dtype: int64

c = df.loc[:, idx[:,'2017']]
print (c)
Country France   UK
Year      2017 2017
Number       1    5
Volume       2    2
Sign up to request clarification or add additional context in comments.

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.