Python按统一半年周期重新采样(相当于pandas重采样中的'BQ')

3 投票
1 回答
2232 浏览
提问于 2025-04-18 17:47

有没有类似于'BQ'的半年度重采样方法可以在Python中使用?我在这里没找到。

http://pandas.pydata.org/pandas-docs/dev/timeseries.html#up-and-downsampling

我有一组记录,其中一些是从六月到十二月的,有些是从一月到七月的,还有一些是从二月到八月的等等。我该如何把它们都重采样到六月到十二月(对于六月到十二月的记录是同时的,其他记录则跟随六月和十二月)呢?

谢谢。

1 个回答

6

'2BQ'怎么样?

In [57]: ts = pd.Series(range(1000), index=pd.date_range('2000-4-15', periods=1000))

In [58]: ts.resample('2BQ', how='sum')
Out[58]: 
2000-06-30      2926
2000-12-29     30485
2001-06-29     63609
2001-12-31     98605
2002-06-28    127985
2002-12-31    166935
2003-06-30      8955
Freq: 2BQ-DEC, dtype: int64

这个2个季度的偏移量是基于数据系列中的第一个时间戳来计算的。所以如果你的数据恰好是从1月到3月或者6月到9月开始的,那个基准点就会不对。解决这个问题的一种方法是,在数据系列的开头填入一个虚拟日期,这样基准点就会正确了。

ts = pd.Series(range(1000), index=pd.date_range('2000-3-15', periods=1000))

from datetime import datetime
if ts.index[0].month in [1,2,3]:
    ts.loc[datetime(ts.index[0].year - 1, 12, 1)] = np.nan
elif ts.index[0].month in [7,8,9]:
    ts.loc[datetime(ts.index[0].year, 6, 1)] = np.nan

这样应该能给出正确的答案(并且可以去掉第一个条目)。

In [85]: ts.resample('2BQ', how='sum')
Out[85]: 
1999-12-31       NaN
2000-06-30      5778
2000-12-29     36127
2001-06-29     69251
2001-12-31    104340
2002-06-28    133534
2002-12-31    150470
Freq: 2BQ-DEC, dtype: float64

撰写回答