Selecting Pandas data by column levels / axis 1 multi-index
Here is a piece of code that does part of what I am trying to do:
selection=df.xs(('year2012','3quarter','A'),level=[0,1,2],axis=1)
How can I select from multiple criteria at each level of axis 1? This might not be the right way to accomplish this.
selection=df.xs(( ['year2012','year2015'] , ['3quarter','4quarter'] , 'A'), level=[0,1,2], axis=1
)
thank
+3
source to share
1 answer
Consider a dataframe example df
mux = pd.MultiIndex.from_product([
['year{}'.format(i) for i in range(2010, 2017)],
['{}quarter'.format(i) for i in range(1, 5)],
list('ABCD')
])
df = pd.DataFrame([np.arange(len(mux))], columns=mux)
df
The way to do this is to use pd.IndexSlice
l1 = ['year2012','year2015']
l2 = ['3quarter','4quarter']
l3 = 'A'
df.loc[:, pd.IndexSlice[l1, l2, l3]]
+2
source to share