8

I was wondering if there is a clean way of selecting or subsetting a Pandas dataframe based on multi index. My data looks like this (id and date are index):

                        values                  
id     date
10113  2010-07-21      24.7000
       2010-07-22      25.2600  
       2010-07-23      25.2800  
       2010-07-26      25.3700 
       2010-07-27      25.2900 
10223  2011-07-21      24.7000
       2011-07-22      25.2600  
       2011-07-23      25.2800  
       2011-07-26      25.3700 
       2011-07-27      25.2900 

I want something like this:

df.xs[10223).xs('2011-07-21':'2011-07-30')

but above code doesn't work for the second xs(). xs() can only select a single row, not a subset of dataframe. I also tried df.query() and df.ix(), but no luck.

Thanks for your help!

1 Answer 1

15

You should be able to use .xs or .ix in the following way:

print df.ix[(10223,'2011-07-21'):(10223,'2011-07-30')]

                 values
id    date              
10223 2011-07-21   24.70
      2011-07-22   25.26
      2011-07-23   25.28
      2011-07-26   25.37
      2011-07-27   25.29

print df.xs(10223,level='id')

            values
date              
2011-07-21   24.70
2011-07-22   25.26
2011-07-23   25.28
2011-07-26   25.37
2011-07-27   25.29

See here for more information

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. First one gives me what I wanted. But second doesn't. Because I only showed a part of data id=10223 have a time series beyond '2011-07-27', I have to slice the date as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.