为大熊猫定义非标准年份

时间:2019-11-12 20:01:14

标签: pandas cumsum

我有一个很长的带有datetime索引的时间序列。我想每年累加,但我想将我的年份定义为明年的10月1日至9月30日。

ex: cum sum on 1 oct 2018 to 30 sept 2019

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

一种方法是将10,11,12手动屏蔽为明年:

# toy data
s = pd.DatetimeIndex(['2017-09-01', '2017-10-01', '2017-11-01'])
df = pd.DataFrame([0,1,2], index=s)

# mask Oct, Nov, Dec
groups = np.where(df.index.month > 9, df.index.year + 1, df.index.year)
# array([2017, 2018, 2018], dtype=int64)

df.groupby(groups).cumsum()

第二种选择是将索引转换为会计年度:

groups = df.index.to_period('Q-SEP').qyear
# Int64Index([2017, 2018, 2018], dtype='int64')

输出:

            0
2017-09-01  0
2017-10-01  1
2017-11-01  3