import pandas as pd
date_index = pd.date_range("2010-01-31", "2010-12-31", freq="M")
df = pd.Series(range(12), index=date_index)
dates = date_index[1::2]
系列df
是每月频率,我们希望通过将dates
变量给出的日期之间的值相加来重新采样。
df
是:
2010-01-31 0
2010-02-28 1
2010-03-31 2
2010-04-30 3
2010-05-31 4
2010-06-30 5
2010-07-31 6
2010-08-31 7
2010-09-30 8
2010-10-31 9
2010-11-30 10
2010-12-31 11
Freq: M, dtype: int64
dates
是
DatetimeIndex(['2010-02-28', '2010-04-30', '2010-06-30', '2010-08-31',
'2010-10-31', '2010-12-31'],
dtype='datetime64[ns]', freq='2M')
预期结果应为:
2010-02-28 1
2010-04-30 5
2010-06-30 9
2010-08-31 13
2010-10-31 17
2010-12-31 21
不是一般的重采样解决方案,而是针对您在可以使用的日期之间将值相加的具体问题
res = df.cumsum()[dates].diff()
res[0] = df[dates[0]]
res = res.astype(df.dtype)
结果:
2010-02-28 1
2010-04-30 5
2010-06-30 9
2010-08-31 13
2010-10-31 17
2010-12-31 21
想法是将不匹配的date
s 值替换为缺失值,方法是用 bacj 填充缺失值的bfill
Series.where
替换,然后聚合sum
:
date_index = pd.date_range("2010-01-31", "2010-12-31", freq="M")
s = pd.Series(range(12), index=date_index)
dates = date_index[1::2]
a = s.index.to_series().where(s.index.isin(dates)).bfill()
out = s.groupby(a).sum()
print(out)
2010-02-28 1
2010-04-30 5
2010-06-30 9
2010-08-31 13
2010-10-31 17
2010-12-31 21
dtype: int64
对于您的特定示例,其中df[0] = 0
,它是一个简单的resample
,具有sum()
聚合,跳过df[0]
。
df_resampled = df[1::].resample('2M').sum()
print(df_resampled)
2010-02-28 1
2010-04-30 5
2010-06-30 9
2010-08-31 13
2010-10-31 17
2010-12-31 21
Freq: 2M, dtype: int64
如果df[0] != 0
,您仍然可以通过将df[0]
添加到df_resampled
的第一个元素来做出简单的解决方法:
df_resampled[0] = df_resampled[0] + df[0]
如果你想要两个月周期的一般重采样,你可以尝试使用resample
的loffset
参数,并提供一个函数返回pd.Timedelta
对象,例如它"地板"到每个月的最后一天。(请参阅此处了解如何获得pd.Timedelta
月经(