【问题标题】:How to split the time series into two based on an anchor date (and week count) in python pandas?python - 如何根据python pandas中的锚定日期(和周数)将时间序列分成两部分?
【发布时间】:2021-05-14 17:17:09
【问题描述】:

这里是时间序列dfdf_curr,以日期时间为索引。

df_curr.head()
                ZONE  REF_WEEK  N_PTS  
WEEK_START                                                                                                                                                     
2018-03-04  Province         1  14196     
2018-03-11  Province         2  14683     
2018-03-18  Province         3  14992     
2018-03-25  Province         4  14168     
2018-04-01  Province         5  14232     

df_curr.tail()
                ZONE  REF_WEEK  N_PTS    
WEEK_START                                                                                                                                             
2020-09-27  Province       135  14547     
2020-10-04  Province       136  14582    
2020-10-11  Province       137  14532     
2020-10-18  Province       138  14555     
2020-10-25  Province       139  14561 

我想生成两个较小的时间序列df_duringdf_pre。最近的时间序列将从2020-03-01 到总共 35 周后(含)。较早的时间序列将在2020-03-01 之前的 35 周。以下代码有效,但我想知道是否有更好的解决方案(我可以将日期比较和 35 周计数结合在一行中)。

start_week = '2020-03-01'
week_n = 35
df_curr = df_curr.sort_index()
df_during = df_curr[df_curr.index >= startweek]
df_during = df_during[:week_n]

df_pre = df_curr[df_curr.index < startweek]
df_pre = df_pre[-week_n:]

【问题讨论】:

    标签: python-3.x pandas time-series


    【解决方案1】:

    这样的事情怎么样:

    df_pre, df_during = df.groupby((df_curr.index - df_curr.index.min()).days/7 >= 35)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2013-04-22
      • 2018-09-16
      • 1970-01-01
      • 2017-01-16
      相关资源
      最近更新 更多