Multiple indexing a combo box data frame

I have a multi-indexed dataframe along the lines:

          score
id  iso
0   AR    1.0203
    BO    1.2303
    CN    1.2402
    NL    1.1202
    SC    1.4552
1   AR    1.2004
    BO    2.3030
    CN    1.2039
    NL    1.6043
    SC    1.3949

      

From this Dataframe I would like to get all the scores for 'id' = 0 for a list of isocodes, for example: ['AR','CN','SC']

By passing in a list of tuples, I manage to get these estimates, for example:

df.ix[[(0,'AR'),(0,'CN'),(0,'SC')],:]

      

leads to:

          score
id  iso
0   AR    1.0203
    CN    1.2402
    SC    1.4552

      

I am currently building a list of tuples before passing it in with ix. Reading http://pandas.pydata.org/pandas-docs/stable/indexing.html#multiindexing-using-slicers I get the feeling that there is a more efficient way to do this than passing in a list of tuples, but I cannot wrap my head is around how to approach it. How to build multi-index slicers in this case?

+3


source to share


1 answer


you can use multiindexing using slicers

>>> idx = pd.IndexSlice
>>> df.loc[idx[0, ['AR','CN','SC']],:]
        score
id iso       
0  AR   1.020
   CN   1.240
   SC   1.455

      

or even simpler:



>>> df.loc[(0, ['AR','CN','SC']),:]

      

or alternatively:

>>> i = df.index.get_level_values(1).isin(['AR','CN','SC'])
>>> j = df.index.get_level_values(0) == 0
>>> df.loc[i & j]

      

+3


source







All Articles