Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas series loc value from multi index

Tags:

python

pandas

I have a series that looks like this

2014  7   2014-07-01   -0.045417
      8   2014-08-01   -0.035876
      9   2014-09-02   -0.030971
      10  2014-10-01   -0.027471
      11  2014-11-03   -0.032968
      12  2014-12-01   -0.031110
2015  1   2015-01-02   -0.028906
      2   2015-02-02   -0.035563
      3   2015-03-02   -0.040338
      4   2015-04-01   -0.032770
      5   2015-05-01   -0.025762
      6   2015-06-01   -0.019746
      7   2015-07-01   -0.018541
      8   2015-08-03   -0.028101
      9   2015-09-01   -0.043237
      10  2015-10-01   -0.053565
      11  2015-11-02   -0.062630
      12  2015-12-01   -0.064618
2016  1   2016-01-04   -0.064852

I want to be able to get the value from a date. Something like:

myseries.loc('2015-10-01') and it returns -0.053565

The index are tuples in the form (2016, 1, 2016-01-04)


2 Answers

You can do it like this:

In [32]:
df.loc(axis=0)[:,:,'2015-10-01']

Out[32]:
                          value
year month date                
2015 10    2015-10-01 -0.053565

You can also pass slice for each level:

In [39]:
df.loc[(slice(None),slice(None),'2015-10-01'),]

Out[39]:
                          value
year month date                
2015 10    2015-10-01 -0.053565|

Or just pass the first 2 index levels:

In [40]:
df.loc[2015,10]

Out[40]:
               value
date                
2015-10-01 -0.053565
like image 113
EdChum Avatar answered May 04 '26 07:05

EdChum


Try xs:

print s.xs('2015-10-01',level=2,axis=0)
#year  datetime 
#2015  10   -0.053565
#Name: series, dtype: float64

print s.xs(7,level=1,axis=0)
#year  datetime  
#2014  2014-07-01   -0.045417
#2015  2015-07-01   -0.018541
#Name: series, dtype: float64
like image 42
jezrael Avatar answered May 04 '26 08:05

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!