Mike
Mike

Reputation: 4269

pandas multiindex selection with ranges

I have a python frame like

 y m     A     B
1990  1  3.4   5
      2  4     4.9
 ...
1990 12  4.0   4.5
 ...
2000  1  2.3   8.1 
      2  3.7   5.0
 ...
2000 12  2.4   9.1

I would like to select 2-12 from the second index (m) and years 1991-2000. I don't seem to get the multindex slicing correct. E.g. I tried

idx = pd.IndexSlice
dfa = df.loc[idx[1:,1:],:]

but that does not seem to slice on the first index. Any suggestions on an elegant solution?

Cheers, Mike

Upvotes: 0

Views: 776

Answers (1)

Primer
Primer

Reputation: 10302

Without a sample code to reproduce your df it is difficult to guess, but if you df is similar to:

import pandas as pd
df = pd.read_csv(pd.io.common.StringIO(""" y m     A     B
1990  1  3.4   5
1990  2  4     4.9
1990 12  4.0   4.5
2000  1  2.3   8.1 
2000  2  3.7   5.0
2000 12  2.4   9.1"""), sep='\s+')

df

      y   m    A    B
0  1990   1  3.4  5.0
1  1990   2  4.0  4.9
2  1990  12  4.0  4.5
3  2000   1  2.3  8.1
4  2000   2  3.7  5.0
5  2000  12  2.4  9.1

Then this code will extract what you need:

print df.loc[(df['y'].isin(range(1990,2001))) & df['m'].isin(range(2,12))]

      y  m    A    B
1  1990  2  4.0  4.9
4  2000  2  3.7  5.0

If however your df is indexes by y and m, then this will do the same:

df.set_index(['y','m'],inplace=True)
years = df.index.get_level_values(0).isin(range(1990,2001))
months = df.index.get_level_values(1).isin(range(2,12))
df.loc[years & months]

      y  m    A    B
1  1990  2  4.0  4.9
4  2000  2  3.7  5.0

Upvotes: 2

Related Questions