简体   繁体   English

如何使用 python 在时间序列数据中创建 3 个月的存储桶

[英]How to create 3 months buckets in time series data with python

I have daily time-series data as date(YYYY-MM-dd) and quantity:我有每日时间序列数据作为日期(YYYY-MM-dd)和数量:

Date        Quantity
2017-10-31      5
2017-11-12      4
2017-11-13      7
2017-11-18      10
2017-12-03      28
2017-12-16      19
2018-01-03      24
2018-01-19      5
2018-02-02      1
2018-03-22      56
2018-04-12      12

I want to create 3 month buckets for date column.我想为日期列创建 3 个月的存储桶。 3M column dates-names can be changed. 3M 列日期名称可以更改。 In below table it represents 2017 between 10 and 12 months.在下表中,它代表 2017 年的 10 到 12 个月。

Date        Quantity    3M
2017-10-31      5       2017-10-12
2017-11-12      4       2017-10-12
2017-11-13      7       2017-10-12
2017-11-18      10      2017-10-12
2017-12-03      28      2017-10-12
2017-12-16      19      2017-10-12
2018-01-03      24      2018-01-03
2018-01-19      5       2018-01-03
2018-02-02      1       2018-01-03
2018-03-22      56      2018-01-03
2018-04-12      12      2018-04-06

How can I do that?我怎样才能做到这一点?

In the end I'll groupby 3M column with sum of Quantity column, so if there is direct way to do that that'll be great.最后,我将按 3M 列和 Quantity 列的总和进行分组,所以如果有直接的方法可以做到这一点,那就太好了。

Any comment would be helpful Thanks,任何评论都会有帮助谢谢,

As of Pandas v0.20.1 (May 5, 2017), pd.cut supports the datetime64 dtype.从 Pandas v0.20.1(2017 年 5 月 5 日)开始, pd.cut支持 datetime64 dtype。

from random import randrange
from datetime import timedelta, date
import numpy as np
import pandas as pd

def random_date(start, end):
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

start = date(2010, 1, 1)
end = date(2020, 1, 1)
df = pd.DataFrame({"dates": [np.datetime64(random_date(start, end)) for _ in range(20)]})
df
bins = pd.date_range(start, end, freq='3MS')

df["bins"] = pd.cut(df.dates, bins=bins)
df

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM