【问题标题】:Fill gaps in time series pandas dataframe in specific time intervall在特定时间间隔内填充时间序列 pandas 数据帧中的空白
【发布时间】:2021-11-12 05:11:45
【问题描述】:

我已经问过一个填补时间序列空白的相关问题
Fill Gaps in time series pandas dataframe
并且 Akshay Sehgal 很友好地给出了一个很好的详细答案!

但是我发现我的数据存在另一个问题。

下面的代码现在可以很好地填补空白,只要有交易日开始和结束的时间戳。
例如,我想填补 09:30 到 16:00 之间时间序列中的所有空白。只要数据中有时间戳,从 09:30 开始到 16:00 结束,这段时间内的所有间隙都由 resample() 填充。
但是,如果当天的数据从 9:45 开始,则重新采样功能将从此时开始填补空白。
但它不会从 09:30 到 09:40 生成新的时间戳(如果我们考虑 5 分钟间隔)

这是我目前使用的代码:

# create new col FillDate from the timestamp (we need this to group the data (otherwise resample would also create new dats and not only times))
df_process['FillDate'] = df_process['Exchange DateTime'].dt.date
# set timestamp as index
df_process.set_index('Exchange DateTime', inplace=True)

# group by for each date, resample missing timestamps and forward fill values
df_process = df_process.groupby('FillDate').resample(rule=update_interval).ffill()

# reset the index and delete the colume Fill Date
df_process_out = df_process.reset_index('FillDate', drop=True).drop('FillDate',1)

但是,无论 09:30 或 16:00 是否有可用的时间戳,我都希望始终在固定时间间隔 09:30 到 16:00 内重新采样。

有什么想法可以有效地解决这个问题吗?

任何帮助/指导将不胜感激 谢谢

【问题讨论】:

    标签: python pandas datetime time-series pandas-resample


    【解决方案1】:

    如果有人感兴趣,我想我找到了解决方案:

       # group the time sires by dates (using the FillDate Column) and than apply 
       # the "Reindex_by_Date" Function to generate the index for each date in the
       # given time frame and fill missing tim stamps 
       df_process = df_process.groupby('FillDate').apply(reindex_by_date, intervall=update_interval)
    
       #drop the helper index "FillDate"
       df_process = df_process.reset_index('FillDate', drop=True).drop('FillDate',1)
    
       # since we reindexed by each date only it can happen that if there is a value missing
       # on the boarder of the index (e.g. last or fist entry) it might have NaN as value
       # we fix this here (we forward fill for example taking the last value from the previous day)
       df_process_out = df_process.fillna(method='ffill')
    
    
       # Helper Function for Closing data gaps with Pandas Groupby and resample
       def reindex_by_date(df, intervall):
            start_range = df.index.date.min().strftime('%Y-%m-%d') +" 09:30:00"
            end_range = df.index.date.max().strftime('%Y-%m-%d') +" 16:00:00"
            dates = pd.date_range(start_range, end_range, freq=intervall)
            return df.reindex(dates).ffill()here
    

    非常欢迎发表评论,或者如果有人有更有效的解决方案,我会非常感兴趣。 谢谢

    【讨论】:

      猜你喜欢
      • 2019-07-02
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多