Pandas:生成带跳跃的连续时间戳

0 投票
1 回答
3729 浏览
提问于 2025-04-18 08:23

我有一个数据框(df),它的索引看起来是这样的:

df.index
>>> [2010-01-04 10:00:00, ..., 2010-12-31 16:00:00]

主要的列是 volume

在时间戳的序列中,有些周末和其他一些工作日是缺失的。我想重新采样我的时间索引,让每分钟的交易量(volume)有一个总和。所以我这样做:

df = df.resample('60S', how=sum)

但是,有些分钟是缺失的。换句话说,有些分钟没有交易记录。我想把这些缺失的分钟也包含进来,并在 volume 列中加上0。

为了解决这个问题,我通常会这样做:

new_range = pd.date_range('20110104 09:30:00','20111231 16:00:00',
                          freq='60s')+df.index
df = df.reindex(new_range)
df = df.between_time(start_time='10:00', end_time='16:00') # time interval per day that I want
df = df.fillna(0)

但是现在我遇到了不想要的日期,比如周末和其他一些天。我该怎么去掉这些原本不在我的时间戳索引中的日期呢?

1 个回答

6

只需要构建你想要的日期时间范围,然后重新调整索引。

整个范围

In [9]: rng = pd.date_range('20130101 09:00','20130110 16:00',freq='30T')

In [10]: rng
Out[10]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 09:00:00, ..., 2013-01-10 16:00:00]
Length: 447, Freq: 30T, Timezone: None

去掉超出范围的时间

In [11]: rng = rng.take(rng.indexer_between_time('09:30','16:00'))

In [12]: rng
Out[12]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 09:30:00, ..., 2013-01-10 16:00:00]
Length: 140, Freq: None, Timezone: None

去掉非工作日

In [13]: rng = rng[rng.weekday<5]

In [14]: rng
Out[14]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2013-01-01 09:30:00, ..., 2013-01-10 16:00:00]
Length: 112, Freq: None, Timezone: None

光看这些值,你可能想用 df.reindex(index=rng) 这个方法。

In [15]: rng.to_series()
Out[15]: 
2013-01-01 09:30:00   2013-01-01 09:30:00
2013-01-01 10:00:00   2013-01-01 10:00:00
2013-01-01 10:30:00   2013-01-01 10:30:00
2013-01-01 11:00:00   2013-01-01 11:00:00
2013-01-01 11:30:00   2013-01-01 11:30:00
2013-01-01 12:00:00   2013-01-01 12:00:00
2013-01-01 12:30:00   2013-01-01 12:30:00
2013-01-01 13:00:00   2013-01-01 13:00:00
2013-01-01 13:30:00   2013-01-01 13:30:00
2013-01-01 14:00:00   2013-01-01 14:00:00
2013-01-01 14:30:00   2013-01-01 14:30:00
2013-01-01 15:00:00   2013-01-01 15:00:00
2013-01-01 15:30:00   2013-01-01 15:30:00
2013-01-01 16:00:00   2013-01-01 16:00:00
2013-01-02 09:30:00   2013-01-02 09:30:00
...
2013-01-09 16:00:00   2013-01-09 16:00:00
2013-01-10 09:30:00   2013-01-10 09:30:00
2013-01-10 10:00:00   2013-01-10 10:00:00
2013-01-10 10:30:00   2013-01-10 10:30:00
2013-01-10 11:00:00   2013-01-10 11:00:00
2013-01-10 11:30:00   2013-01-10 11:30:00
2013-01-10 12:00:00   2013-01-10 12:00:00
2013-01-10 12:30:00   2013-01-10 12:30:00
2013-01-10 13:00:00   2013-01-10 13:00:00
2013-01-10 13:30:00   2013-01-10 13:30:00
2013-01-10 14:00:00   2013-01-10 14:00:00
2013-01-10 14:30:00   2013-01-10 14:30:00
2013-01-10 15:00:00   2013-01-10 15:00:00
2013-01-10 15:30:00   2013-01-10 15:30:00
2013-01-10 16:00:00   2013-01-10 16:00:00
Length: 112

你也可以先构建一个工作日频率的序列(如果你想要假期的话,还可以添加自定义的工作日,这在0.14.0版本中新增,具体可以查看这里)。

撰写回答