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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With