For each calendar month in s, find the mean of values. Assume import pandas as pd and import numpy as np. Starting data:
PythonLevel: Intermediate
For each calendar month in s, find the mean of values.
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.resample('ME').mean()
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