I have a dataframe with daily stock data for the last 10 years, here is a slice of the dataframe :
ITUB4 ITUB3
DATE
2007-04-26 13.46 11.12
2007-04-27 13.49 11.00
2007-04-30 13.19 10.92
2007-05-02 13.57 11.09
2007-05-03 13.90 11.25
... ... ...
2017-12-21 42.72 37.39
2017-12-22 42.52 36.99
2017-12-26 42.69 37.44
2017-12-27 42.46 37.46
2017-12-28 42.57 37.68
2641 rows × 2 columns
Is there an easy way to slice this dataframe per year ? I know it is possible to do it by using :
df['20061230':'20071231']
I was wondering if there was something like :
df.index.year['2017']
You can use df['2017']
or df.loc['2017']
. pandas is smart enough to understand it is the year part of a DateTimeIndex (see docs).
I prefer loc
as it is more obvious this is an index operation - not a column one.
df.loc['2017']
Out:
ITUB4 ITUB3
DATE
2017-12-21 42.72 37.39
2017-12-22 42.52 36.99
2017-12-26 42.69 37.44
2017-12-27 42.46 37.46
2017-12-28 42.57 37.68
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