Python Pandas如何在特定时间范围内填充缺失数据

3

我有一个类似于这样的pandas数据框:

enter image description here

正如您所看到的 - 在日期时间索引中,有某些分钟缺失。例如,在屏幕截图中,第一行和第二行之间缺少了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"
  }
}
1个回答

4
我建议您使用pandas的resample方法。它将数据框重新采样为指定的格式,步骤如下:
  1. 使用pandas的resample方法进行重新采样。'1T'代表分钟。您可以在这里查看其他频率:https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases

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

  3. 之后,将'volume'中的缺失值填充为0,并向前填充其余列。

  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')

谢谢,这已经满足了我所有的要求!然而,这暴露出一个新问题——数据框现在显示了周末和原本不在数据框中的节假日的值。有没有办法排除那些不在数据框中的日期? - Abhay
1
是的,我已经编辑了我的答案以满足您的要求。 - RVA92

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接