首页 > 解决方案 > 查找以 1 分钟间隔采样的 pandas 时间序列数据帧中的空白,并用新行填补空白

问题描述

问题

我有一个数据框,其中包含每隔 1 分钟采样的财务数据。有时可能会丢失一两行数据。

例如:

 #Example Input---------------------------------------------
                      open     high     low      close
 2019-02-07 16:01:00  124.624  124.627  124.647  124.617  
 2019-02-07 16:04:00  124.646  124.655  124.664  124.645  

 # Desired Ouput--------------------------------------------
                      open     high     low      close
 2019-02-07 16:01:00  124.624  124.627  124.647  124.617  
 2019-02-07 16:02:00  NaN      NaN      NaN      NaN
 2019-02-07 16:03:00  NaN      NaN      NaN      NaN
 2019-02-07 16:04:00  124.646  124.655  124.664  124.645 

我目前的方法基于这篇文章 - Find missing minute data in time series data using pandas - 仅建议如何识别差距。不是如何填充它们。

我正在做的是创建一个间隔为 1 分钟的 DateTimeIndex。然后使用这个索引,我创建了一个全新的数据帧,然后可以将其合并到我的原始数据帧中,从而填补空白。代码如下所示。这似乎是一个关于这样做的方式。我想知道是否有更好的方法。也许重新采样数据?

import pandas as pd
from datetime import datetime

# Initialise prices dataframe with missing data
prices = pd.DataFrame([[datetime(2019,2,7,16,0),  124.634,  124.624, 124.65,   124.62],[datetime(2019,2,7,16,4), 124.624,  124.627,  124.647,  124.617]])
prices.columns = ['datetime','open','high','low','close']
prices = prices.set_index('datetime')
print(prices)

# Create a new dataframe with complete set of time intervals
idx_ref = pd.DatetimeIndex(start=datetime(2019,2,7,16,0), end=datetime(2019,2,7,16,4),freq='min')
df = pd.DataFrame(index=idx_ref)

# Merge the two dataframes 
prices = pd.merge(df, prices, how='outer', left_index=True, 
right_index=True)
print(prices)

标签: pythonpython-3.xpandas

解决方案


使用:DataFrame.asfreq_Datetimeindex

prices = prices.set_index('datetime').asfreq('1Min')
print(prices)
                        open     high      low    close
datetime                                               
2019-02-07 16:00:00  124.634  124.624  124.650  124.620
2019-02-07 16:01:00      NaN      NaN      NaN      NaN
2019-02-07 16:02:00      NaN      NaN      NaN      NaN
2019-02-07 16:03:00      NaN      NaN      NaN      NaN
2019-02-07 16:04:00  124.624  124.627  124.647  124.617

推荐阅读