我正在努力寻找一种正确的方法来解决使用 pandas 进行重采样的问题,而不是使用可能容易出错的丑陋技巧。
假设我有这样一个系列:
dates = pd.date_range('2018-01-03', '2018-09-13')
s = pd.Series(range(len(dates)), index=dates)
现在,我想将系列重新采样到月份,但从索引的第一个日期开始,而不是从月份的第一天开始。例如,如果我只是重新采样到“MS”,我得到的第一个日期是 2018-01-01,而不是 2018-01-03;当然,它是“月开始”,所以这是我应该期望的,但是我如何才能每月重新采样而不是从月初而不是从同一月的一天开始选择样本,这样得到的索引将是比如 ["2018-01-03", "2018-02-03", 等等]?
换句话说,我如何使用“从索引中的第一个日期时间开始的月份”之类的内容重新采样?
到目前为止,我找到的唯一方法是在系列中创建一些前导日期,然后进行负偏移,然后使用 loffset 参数(因为 shift 和 loffset 都不考虑数据与索引),但这是一个非常丑陋的 hack,我想避免。
谢谢!
[解决方案]
我通过这些简单的步骤解决了这个问题,并根据解决此问题的多次尝试进行了调整(包括下面的第一个回复,以及来自 SO 的其他站点和问题):
dates = pd.date_range('2018-01-03', '2018-09-13')
s = pd.Series(range(len(dates)), index=dates)
delta = dates.min() - (dates.min() - offsets.MonthBegin(1))
new_dates = dates - delta
s2 = s.copy()
s2.index = new_dates
resampled = s2.resample('MS', loffset=delta)
r_max = resampled.max()
r_min = resampled.min()
r_mean = resampled.mean()
r_sum = resampled.sum()
print('s\n', s)
print('r_max\n', r_max)
print('r_min\n', r_min)
print('r_mean\n', r_mean)
print('r_sum\n', r_sum)
感谢您的帮助!
[编辑] 替代解决方案
我最终对此采取了一些不同的方法。我从这样的事情开始:
dates = pd.date_range('2015-01-31', '2018-09-13')
start_date: dt.date = dates[0].date()
end_date: dt.date = dates[-1].date()
recurrent_dates = []
next_date = start_date
while next_date <= end_date:
if next_date.day < start_date.day:
try:
next_date = dt.date(
next_date.year, next_date.month, start_date.day)
except ValueError:
next_date = (
next_date + offsets.MonthBegin(1) - offsets.Day(1)
).date()
recurrent_dates.append(next_date)
next_date += relativedelta(months=1)
要预期从任意日期开始的月度周期,然后使用上面的循环日期创建一个 DataFrame,然后使用 fillna(method="ffill") 使用原始 DataFrame 中的日期重新索引它,然后使用 groupby 按重复日期。
希望这对其他人也有帮助。
请您参考如下方法:
获取每月系列
dates = pd.date_range(s.index.min(), s.index.max(), freq='M')
返回到第一个日期之前的 MonthEnd 并添加天数
dates = dates + pd.offsets.MonthEnd(-1) + pd.offsets.Day(s.index[0].day)
使用重新索引
s.reindex(dates)
2018-01-03 0
2018-02-03 31
2018-03-03 59
2018-04-03 90
2018-05-03 120
2018-06-03 151
2018-07-03 181
2018-08-03 212
dtype: int64
