代码之家  ›  专栏  ›  技术社区  ›  user3017048

具有自定义年初数据集统计信息

  •  0
  • user3017048  · 技术社区  · 7 年前

    我尝试了以下方法:

    rollday = -181
    dr = pd.date_range('2015-01-01', '2017-08-23')
    foo = xr.Dataset({'data': (['time'], np.ones(len(dr)))}, coords={'time': dr})
    foo_groups = foo.roll(time=rollday).groupby(foo.time.dt.year)
    foo_cumsum = foo_groups.apply(lambda x: x.cumsum(dim='time', skipna=True))
    

    这是“不利的”,主要是因为两件事: (2) 第一年的开始(直到6月底)被附加到滚动时间序列的末尾,这会创建一些“假年份”,其中累积总和不再有意义。

    我也试着先剪掉时间序列的末端,但之后滚动就不再有效了。对我来说,重新采样似乎也不是一个选项,因为我找不到合适的pandas频率字符串。

    我确信有更好/正确的方法来做到这一点。有人能帮忙吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   jhamman    6 年前

    你可以使用 xarray.DataArray 它指定了组。一种方法是创建定义组ID的值(年)数组:

    # setup sample data
    dr = pd.date_range('2015-01-01', '2017-08-23')
    foo = xr.Dataset({'data': (['time'], np.ones(len(dr)))}, coords={'time': dr})
    
    # create an array of years (modify day/month for your use case)
    my_years = xr.DataArray([t.year if ((t.month < 9) or ((t.month==9) and (t.day < 15))) else (t.year + 1) for t in foo.indexes['time']],
                            dims='time', name='my_years', coords={'time': dr})
    
    # use that array of years (integers) to do the groupby
    foo_cumsum = foo.groupby(my_years).apply(lambda x: x.cumsum(dim='time', skipna=True))
    
    # Voila!
    foo_cumsum['data'].plot()
    

    enter image description here