Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset a data frame based on index value [duplicate]

Tags:

python

pandas

I've got a data frame of weekly stock price returns that are indexed by date, as follows.

            FTSE_350    SP_500
2005-01-14 -0.004498 -0.001408
2005-01-21  0.001287 -0.014056
2005-01-28  0.011469  0.002988
2005-02-04  0.016406  0.027037
2005-02-11  0.015315  0.001887 

I would like to return a data frame of rows where the index is in some interval, let's say all dates in January 2005. I'm aware that I could do this by turning the index into a "Date" column, but I was wondering if there's any way to do this directly.

like image 839
T. Hannigan Avatar asked Sep 12 '18 02:09

T. Hannigan


1 Answers

Yup, there is, even simpler than doing a column!

Using .loc function, then just slice the dates out, like:

print(df.loc['2005-01-01':'2005-01-31'])

Output:

            FTSE_350    SP_500
2005-01-14 -0.004498 -0.001408
2005-01-21  0.001287 -0.014056
2005-01-28  0.011469  0.002988

Btw, if index are objects, do:

df.index = pd.to_datetime(df.index)

before everything.

As @Peter mentioned The best is:

print(df.loc['2005-01'])

Also outputs:

            FTSE_350    SP_500
2005-01-14 -0.004498 -0.001408
2005-01-21  0.001287 -0.014056
2005-01-28  0.011469  0.002988
like image 115
U12-Forward Avatar answered Nov 02 '22 01:11

U12-Forward