Search code examples
pandasdatetimetime-seriesstockpandas-resample

Output last row of each year


My dataframe look like this:

            Close   Volume  Dividends
Date                                 
2014-08-07  14.21  4848000       0.00
2014-08-08  13.95  5334000       0.00
2014-08-11  14.07  4057000       0.00
2014-08-12  14.13  2611000       0.00
2014-08-13  14.15  3743000       0.28
...           ...      ...        ...
2020-08-03  19.45  7352600       0.00
2020-08-04  19.69  4250500       0.00
2020-08-05  19.83  3414080       0.00
2020-08-06  20.40  6128100       0.00
2020-08-07  20.60  8295000       0.00

I like to output the closing price for the last day of each year. I tried the following:

df = df.groupby(df.index.year)['Close'].tail(1)

Date
2014-12-31    16.39
2015-12-31    13.67
2016-12-30    14.78
2017-12-29    21.83
2018-12-31    21.64
2019-12-31    25.00
2020-08-07    20.60

I want the output to be:

Date
2014  16.39
2015  13.67
2016  14.78
2017  21.83
...

Any help would be very much appreciated. Many Thanks!


Solution

  • Try with last

    df = df.groupby(df.index.year)['Close'].last()