我有一个包含多个标题的df:
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)
我想打印2018年的法国专栏。
我该怎么做?
答案 0 :(得分:0)
使用元组选择MultiIndex
中的选择列:
df = df[('France','2018')]
print (df)
Number 2
Volume 4
Name: (France, 2018), dtype: int64
对于更复杂的选择,请使用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