Olaf
Olaf

Reputation: 55

Multi-index slicing of dataframe with list

I have a multi-indexed dataframe along the lines of:

          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'd like to get all the scores for 'id' = 0 for a list of iso codes, for example: ['AR','CN','SC']

Passing a list of tuples, I manage to get these scores, for example:

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

results in:

          score
id  iso
0   AR    1.0203
    CN    1.2402
    SC    1.4552

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

Upvotes: 3

Views: 346

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77991

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]

Upvotes: 3

Related Questions