• python数据分析之:时间序列二


    Timestamp转换为Period

    通过使用to_period方法,可以将由时间戳索引的SeriesDataFrame对象转换为以时期索引

    rng=pd.date_range('1/1/2000',periods=3,freq='M')

    ts=Series(randn(3),index=rng)

    print(ts)

    pts2=ts.to_period(freq='M')

    print(pts2)

    结果如下:ts是每个月最后一天的日期,pts2则是体现的是以月为周期的日子

    2000-01-31    0.990097

    2000-02-29    0.439761

    2000-03-31   -3.395317

    Freq: M, dtype: float64

    2000-01    0.990097

    2000-02    0.439761

    2000-03   -3.395317

    Freq: M, dtype: float64

    如果要转换回时间戳,则可以使用pts2.to_timestamp(how='end')的方法

    2000-01-31   -0.489228

    2000-02-29   -1.583283

    2000-03-31   -2.414735

    Freq: M, dtype: float64

    重采样及频率转换

    将高频率数据转换为低频率称为降采样,而将低频率数据转换为高频率称为升采样。pandas中的resample方法就可以进行这种频率转换

    rng=pd.date_range('1/1/2000',periods=50,freq='D')

    ts=Series(randn(50),index=rng)

    print(ts.resample('M').mean())

    运行结果如下,在这里ts是以天级的数据,但是通过resample(‘M’)转换为月度的数据,且对属于同一个月的数据进行求平均的计算。得到的就是每个月的平均值

    2000-01-31   -0.276265

    2000-02-29   -0.052926

    Freq: M, dtype: float64

    降采样:

    在降采样的时候,需要考虑两样东西:

    各区间哪边是闭合的

    如何标记各个聚合面元,用区间的开头还是末尾

    来看如下代码:

    rng=pd.date_range('1/1/2000',periods=12,freq='T')

    ts=Series(np.arange(12),index=rng)

    print(ts)

    2000-01-01 00:00:00     0

    2000-01-01 00:01:00     1

    2000-01-01 00:02:00     2

    2000-01-01 00:03:00     3

    2000-01-01 00:04:00     4

    2000-01-01 00:05:00     5

    2000-01-01 00:06:00     6

    2000-01-01 00:07:00     7

    2000-01-01 00:08:00     8

    2000-01-01 00:09:00     9

    2000-01-01 00:10:00    10

    2000-01-01 00:11:00    11

    print(ts.resample('5min', closed='left').sum())

    左闭合的时候统计是以00:00:00为开始的5分钟周期

    2000-01-01 00:00:00    10

    2000-01-01 00:05:00    35

    2000-01-01 00:10:00    21

    print(ts.resample('5min',closed='right').sum())

    右闭合的时候统计是以00:00:00结束的5分钟周期,因为时间提前到了1999-12-31 23:55:00这个时候。

    1999-12-31 23:55:00     0

    2000-01-01 00:00:00    15

    2000-01-01 00:05:00    40

    2000-01-01 00:10:00    11

    因此左闭合还是右闭合取决与时间的开始和结束

    在金融领域中有一种无所不在的时间序列聚合方式,即计算各面元的4个值,第一个值open:开盘,最后一个值close:收盘,最大值high:最高,最小值low:最低

    ts.resample('5min', closed='left').ohlc()

                         open  high  low  close

    2000-01-01 00:00:00     0     4    0      4

    2000-01-01 00:05:00     5     9    5      9

    2000-01-01 00:10:00    10    11   10     11

  • 相关阅读:
    贮油点问题(C++)
    二维数组操作
    二的幂次方(递归)
    [haoi2009]巧克力
    距离最远的牛
    ssh注解basedao简单的实现
    @service中构造方法报错
    spring注解 构造函数问题
    json与gson
    AsyncTask异步类的简单操作
  • 原文地址:https://www.cnblogs.com/zhanghongfeng/p/8859047.html
Copyright © 2020-2023  润新知