在特定时间间隔内填补时间序列 pandas 数据帧中的空白

Fill gaps in time series pandas dataframe in specific time intervall

我已经问了一个相关的填补时间序列空白的问题

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 是否有可用的时间戳。

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

任何 help/guidance 将不胜感激 谢谢

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

   # 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

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