简体   繁体   中英

Selecting Pandas data by column levels/ axis 1 multi-index

Here is a piece of code that accomplishes part of what I'm trying to do:

selection=df.xs(('year2012','3quarter','A'),level=[0,1,2],axis=1)

How can I make a selection of multiple criteria in each level of axis 1? The following seems to be the wrong way to accomplish this.

selection=df.xs(( ['year2012','year2015'] , ['3quarter','4quarter'] , 'A'), level=[0,1,2], axis=1 )

Thank you

Consider the example dataframe 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]]

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM