首页 > 解决方案 > Python Pandas 前向填充特定时间范围内的缺失数据

问题描述

我有一个看起来像这样的熊猫数据框:

在此处输入图像描述

如您所见 - 在日期时间索引中,缺少某些分钟。例如,在屏幕截图中,第一行和第二行之间缺少 9:16:00 - 9:19:00 分钟。我想将前一分钟的数据转发到所有丢失的分钟。

现在,我们到达了它变得复杂的部分 - 以及我需要帮助的部分。我只需要在每个日期的 09:15:00 到 15:30:00 之间转发填充分钟。并且,对于任何前向填充的行,该列Volume的值应为0

为了帮助您探索数据,我已将前几行导出到 json 对象(我认为日期时间索引已转换为毫秒)

    {
  "1580464080000": {
    "expiry": "4/30/2020",
    "close": 12157.3,
    "high": 12157.3,
    "volume": 0,

    "open": 12157.3,
    "low": 12157.3,
    "timezone": "+05:30"
  },
  "1580463120000": {
    "expiry": "4/30/2020",
    "close": 12200.3,
    "high": 12200.3,
    "volume": 0,
    "open": 12200.3,
    "low": 12200.3,
    "timezone": "+05:30"
  },
  "1580464260000": {
    "expiry": "4/30/2020",
    "close": 12150.0,
    "high": 12150.0,

    "volume": 0,
    "open": 12150.0,
    "low": 12150.0,
    "timezone": "+05:30"
  },
  "1580462400000": {
    "expiry": "4/30/2020",
    "close": 12174.0,
    "high": 12174.0,
    "volume": 0,
    "open": 12174.0,
    "low": 12174.0,
    "timezone": "+05:30"
  },
  "1580462820000": {
    "expiry": "4/30/2020",
    "close": 12193.7,
    "high": 12193.7,
    "volume": 0,
    "open": 12193.7,
    "low": 12193.7,
    "timezone": "+05:30"
  },
  "1580462100000": {
    "expiry": "4/30/2020",
    "close": 12180.0,
    "high": 12180.0,
    "volume": 0,
    "open": 12180.0,
    "low": 12180.0,
    "timezone": "+05:30"
  },
  "1580464440000": {
    "expiry": "4/30/2020",
    "close": 12160.45,
    "high": 12160.45,
    "volume": 0,
    "open": 12160.45,
    "low": 12160.45,
    "timezone": "+05:30"
  }
}

标签: python-3.xpandasdataframedatetimeindex

解决方案


我建议你使用 pandas resample 方法。它将数据帧重新采样为指定的格式。步骤是:

  1. 使用 pandas 重采样方法重采样。'1T' 是分钟。您可以在此处查看其他频率:https ://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases

  2. 然后使用 between_time 删除不需要的时间,即在 9:15 到 15:30 之外。

  3. 然后用 0 填写“volume”的 NA 并向前填充剩余的列。

  4. 向前填充剩余的列

这是一个示例代码:

# Get unique dates from the data frame
df['Date'] = df.index.date
sample_days = df['Date'].unique()

# Resample to 1 minute and keep only the original dates
df = df.resample('1t').last()
df = df.loc[df['Date'].isin(sample_days)]

# Remove non open hours
df = df.between_time('09:15', '15:30')

# Fill 0 in Na for volume
df['volume'] = df['volume'].fillna(0)

# Forward fill the remaining columns (notice, as NAs in volume are removed, it does effect this column)
df = df.fillna(method='ffill')

推荐阅读