Skip to content
Quantoros

For each group of four consecutive calendar months in s, find the date on which the highest value occurred. Assume…

PythonLevel: Intermediate

For each group of four consecutive calendar months in s, find the date on which the highest value occurred.

Assume import pandas as pd and import numpy as np.

Starting data:

dti = pd.date_range(start='2015-01-01', end='2015-12-31', freq='B') 
s = pd.Series(np.random.rand(len(dti)), index=dti)
Hints
  • First define row granularity, column types and keys.
  • Check index alignment, missing values and output size after the transformation.

Answer

s.groupby(pd.Grouper(freq='4ME')).idxmax()

Editorial compatibility note: the original month-end alias M is updated to ME for pandas 2.2+ (release notes).

Source and licence: 100 pandas puzzles — Alex Riley and contributors · MIT

Related questions