Pandas 重新采样时间序列向后计数(或反向重新采样)

2023-12-07

我想重新采样倒数的 pandas 时间序列。例如,让我们设置一个 11 天的简单时间序列:

>>> index = pd.date_range('01-01-2018', '01-11-2018', freq='D')
>>> randint = np.random.randint(low=0, high=9, size=(len(index), 1))

>>> df = pd.DataFrame(randint, index=index, columns=['random'])
>>> print(df)

            random
2018-01-01       8
2018-01-02       8
2018-01-03       1
2018-01-04       4
2018-01-05       3
2018-01-06       5
2018-01-07       2
2018-01-08       6
2018-01-09       5
2018-01-10       1
2018-01-11       3

默认的 pandas 行为

如果我每 5 天重新采样一次,我会得到:

>>> df_5d = df.resample('5D').sum()
>>> print(df_5d)

            random
2018-01-01      24
2018-01-06      19
2018-01-11       3

基本上有 3 组:前两组有 5 名成员,最后一组有 1 名成员,总共 11 名成员:

Start        End
2018-01-01   2018-01-05
2018-01-06   2018-01-10
2018-01-11   2018-01-11

我想要的是这个

>>> df_5d = df.resample('5D').sum()
>>> print(df_5d)

            random
2018-01-01       8
2018-01-02      21
2018-01-07      17

分组如下所示。看我怎么数的'5D'从最新日期开始倒推:

Start        End
2018-01-01   2018-01-01
2018-01-02   2018-01-06
2018-01-07   2018-01-11

如何对倒数的 Pandas 时间序列进行重新采样?


解决方法可能是划分您的原始df分成两部分,以便能够使用标准重采样,然后pd.concat两个数据帧都重新采样,例如:

res_interval = 5
df_res = pd.concat([df[:len(df)%res_interval].resample('{}D'.format(res_interval)).sum(),
                    df[len(df)%res_interval:].resample('{}D'.format(res_interval)).sum()])

通过我的随机数,我得到:

            random
2018-01-01       1
2018-01-02      13
2018-01-07      26
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 重新采样时间序列向后计数(或反向重新采样) 的相关文章

随机推荐