Skip to content
Advertisement

Find max by year and return date on which max occurred in Pandas with dates as index

I have this dataframe

JavaScript

I would like to compute the max for each year and the date where it happens. I am struggling because I would like to keep indeed the date as index.

Indeed I read it as:

JavaScript

I know that I could resample as

JavaScript

but in this case I would lose the information about the location of the maximum value within the year.

I have found this:

JavaScript

However, dfr[‘date’] seems to be the name of the column while in my case date in an index and ‘.year’ is not one of its properties.

I have the felling that I should work with “groupby” and “indexmax”. However, all the attends that I made, they all failed.

Thanks in advance

Advertisement

Answer

Assuming “date” is of datetime type and a column, you can use the following to slice your data with the maximum per group:

JavaScript

output:

JavaScript

If “date” is the index:

JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement