在以1分钟为间隔采样的熊猫时间序列数据框中找到空白,并用新行填充空白

Arr*_*uff 2 python python-3.x 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 
Run Code Online (Sandbox Code Playgroud)

我当前的方法基于此帖子- 使用熊猫在时间序列数据中查找丢失的分钟数据 -仅建议如何识别差距。不是如何填充它们。

我正在做的是创建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)
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

使用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
Run Code Online (Sandbox Code Playgroud)