python - 查找以 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)
解决方案
使用: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
推荐阅读
- react-native - 更改图像背景 onClick
- php - 如何从 php 中的表单中获取文件名?$_FILES["filename"]["name"] 似乎不起作用
- laravel - Laravel 测试结果不准确
- java - 转换列表
使用 java 流转换为字符串 - ssl - Quarkus TLS 异常:DefaultChannelPipeline] (vert.x-eventloop-thread-0) 触发了 exceptionCaught() 事件
- javascript - 如何将图像上传到 Editor.js 的 Firebase 存储?
- html - 下拉菜单不会在第二次点击/触摸时关闭
- python - 我可以使用哪些 pyqt 小部件,其中我可以显示图片并同时显示文本
- javascript - 如何处理和计算 - 没有 For 循环的两个数组对象
- python - 当字符串只是列表项的一部分时,如何在列表中查找所有出现的字符串