Skip to main content
 首页 » 编程设计

python之更改 Pandas 时间戳的开始和结束时间

2025年05月04日10me-sa

我正在处理一个数据集,其中的观察发生在开放时间和关闭时间之间——但服务在开放后的第二天关闭。例如,开市时间为早上 7 点,闭市时间为次日凌晨 1 点。

这感觉像是一个非常普遍的问题——我四处搜索它,并且坦诚地接受这样一个事实,即我可能只是不知道要搜索的正确术语。

对于我的大部分用途来说,执行以下操作就足够了:

   open_close = pd.DatetimeIndex(start='2012-01-01 05:00:00', periods = 15, offset='D') 

然后我可以在 df 上做有趣的小 groupbys:
df.groupby(open_close.asof).agg(func).

但是我遇到了一个实例,我需要获取多个这样的打开-关闭周期。我真正想要做的只是有一个 DatetimeIndex,我可以在一天开始时选择它。所以我可以将“天”重新定义为从早上 5 点到早上 5 点。这样做的好处是,我可以使用 df[df.index.dayofweek == 6] 之类的东西,从周日早上 5 点到周一早上 5 点取回所有内容。

感觉就像句点......或者 pandas 内部的某些东西预料到了这个请求。很乐意帮助解决这个问题。

编辑:

我还通过在正确的日期创建另一列来解决这个问题
df['shift_day'] = df['datetime'].apply(magicFunctionToFigureOutOpenClose)
——所以这并没有阻碍我的进步。感觉就像是可以很好地集成到包中的东西(或日期时间......或某处......)

请您参考如下方法:

也许 df.resample() 的 base 参数会有所帮助:

base : int, default 0 
    For frequencies that evenly subdivide 1 day, the "origin" of the 
    aggregated intervals. For example, for '5min' frequency, base could 
    range from 0 through 4. Defaults to 0 

这是一个例子:

In [44]: df = pd.DataFrame(np.random.rand(28), 
....:           index=pd.DatetimeIndex(start='2012/9/1', periods=28, freq='H')) 
 
In [45]: df 
Out[45]:  
                            0 
2012-09-01 00:00:00  0.970273 
2012-09-01 01:00:00  0.730171 
2012-09-01 02:00:00  0.508588 
2012-09-01 03:00:00  0.535351 
2012-09-01 04:00:00  0.940255 
2012-09-01 05:00:00  0.143483 
2012-09-01 06:00:00  0.792659 
2012-09-01 07:00:00  0.231413 
2012-09-01 08:00:00  0.071676 
2012-09-01 09:00:00  0.995202 
2012-09-01 10:00:00  0.236551 
2012-09-01 11:00:00  0.904853 
2012-09-01 12:00:00  0.652873 
2012-09-01 13:00:00  0.488400 
2012-09-01 14:00:00  0.396647 
2012-09-01 15:00:00  0.967261 
2012-09-01 16:00:00  0.554188 
2012-09-01 17:00:00  0.884086 
2012-09-01 18:00:00  0.418577 
2012-09-01 19:00:00  0.189584 
2012-09-01 20:00:00  0.577041 
2012-09-01 21:00:00  0.100332 
2012-09-01 22:00:00  0.294672 
2012-09-01 23:00:00  0.925425 
2012-09-02 00:00:00  0.630807 
2012-09-02 01:00:00  0.400261 
2012-09-02 02:00:00  0.156469 
2012-09-02 03:00:00  0.658608 

In [46]: df.resample("24H", how=sum, label='left', closed='left', base=5) 
Out[46]:  
                             0 
2012-08-31 05:00:00   3.684638 
2012-09-01 05:00:00  11.671068 
 
In [47]: df.ix[:5].sum() 
Out[47]: 0    3.684638 
 
In [48]: df.ix[5:].sum() 
Out[48]: 0    11.671068