I have a question regarding the resampling method of pandas Dataframes.
I have a DataFrame with one observation per day:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(366, 1)), columns=list('A'))
df.index = pd.date_range(datetime.date(2016,1,1),datetime.date(2016,12,31))
if I want to compute the sum (or other) for every month, I can directly do:
EOM_sum = df.resample(rule="M").sum()
however I have a specific calendar (irregular frequency):
import datetime
custom_dates = pd.DatetimeIndex([datetime.date(2016,1,13),
datetime.date(2016,2,8),
datetime.date(2016,3,16),
datetime.date(2016,4,10),
datetime.date(2016,5,13),
datetime.date(2016,6,17),
datetime.date(2016,7,12),
datetime.date(2016,8,11),
datetime.date(2016,9,10),
datetime.date(2016,10,9),
datetime.date(2016,11,14),
datetime.date(2016,12,19),
datetime.date(2016,12,31)])
If I want to compute the sum for each period, I currently add a temporary column to df with the end of the period each row belongs to, and then perform the operation with a groupby:
df["period"] = custom_dates[custom_dates.searchsorted(df.index)]
custom_sum = df.groupby(by=['period']).sum()
However this is quite dirty and doesn't look pythonic. Is there a built-in method to do this in Pandas?
Thanks in advance.
See Question&Answers more detail:
os