9

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.

T. Hannigan
  • 93
  • 1
  • 1
  • 4

1 Answers1

18

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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 3
    Nice answer. Also works: `df.loc['2005-01']`. And if the index in the OP happens to be of type string, `df.index = pd.to_datetime(df.index)` should fix that. – Peter Leimbigler Sep 12 '18 at 02:32