熊猫如何在6个月内重新采样?

时间:2019-08-14 01:21:56

标签: python pandas

我正在尝试做一个简单的重采样,以汇总6个月内的值。为了解释我的问题,我创建了一个简单的玩具系列:

import pandas as pd
import numpy as np

series = pd.Series([1,2,5,6], index=[pd.Timestamp('2018-01-01'), pd.Timestamp('2018-06-30'),pd.Timestamp('2018-07-01'), pd.Timestamp('2018-12-31')])
series

2018-01-01    1
2018-06-30    2
2018-07-01    5
2018-12-31    6
dtype: int64

现在,我尝试在2个半年中重新采样,第一个我想从2018-01-01到2018-06-30,然后求和3,第二个我想从2018-07-01到2018- 12-31和11。

这就是我得到的:

series.resample('2Q').sum()
2018-03-31    1
2018-09-30    7
2019-03-31    6
Freq: 2Q-DEC, dtype: int64

series.resample('6M', closed='left').sum()
2018-06-30    1
2018-12-31    7
2019-06-30    6
Freq: 6M, dtype: int64

我没有想要的。我看到了有关每6个月进行一次重新采样(How to resample 6 months)的其他问题,但没有一个问题表明如何防止这种特定行为。

2 个答案:

答案 0 :(得分:1)

我通过将频率更改为“四分之一开始”和“月开始”来使其正常工作,但仍然不了解其逻辑:

series.resample('2QS').sum()
2018-01-01     3
2018-07-01    11
Freq: 2QS-JAN, dtype: int64

series.resample('6MS').sum()
2018-01-01     3
2018-07-01    11
Freq: 6MS, dtype: int64

答案 1 :(得分:0)

这里是一种方式:0表示前半部1表示后半部

series.groupby([series.index.year,(series.index.month-1)//6]).sum()
Out[489]: 
2018  0     3
      1    11
dtype: int64