基于自定义工作小时创建熊猫多级索引

2024-04-16 13:53:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

             datetime    price  tickvol      bid      ask
0 2016-10-11 12:24:03  2130.25        1  2130.00  2130.25
1 2016-10-11 13:31:03  2130.25        1  2130.00  2130.25
...

我有一个定制的工作时间,看起来像这样:

cbh = CustomBusinessHour(start='13:30', end='13:15', weekmask='Sun Mon Tue Wed Thu')

我希望我可以使用自定义工作时间的开始时间戳创建一个新的索引级别,但是我在工作中遇到了问题。你知道吗

我希望得到的是:

                cbh            datetime    price  tickvol      bid      ask
2016-10-10 13:30:00 2016-10-11 12:24:03  2130.25        1  2130.00  2130.25
2016-10-11 13:30:00 2016-10-11 13:31:03  2130.25        1  2130.00  2130.25

Tags: 数据datetime时间startpriceaskendsun
1条回答
网友
1楼 · 发布于 2024-04-16 13:53:38

这就是我最后要做的。它是有效的,但可能会得到改进。似乎CustomBusinessHour并没有直接公开任何确定时间是进入还是结束的方法。你知道吗

def session_start(ts, cbh):
    """Given a timestamp and a CustomBusinessHour, return the session start
    timestamp"""
    assert type(ts) == pd.Timestamp
    spans = spans_midnight(cbh)
    t = ts.time()
    if spans:
        if cbh.end <= t < cbh.start:
            return pd.NaT
        elif t < cbh.start:
            # this timestamp is part of the previous calendar day session
            ts = ts.replace(day=ts.day - 1)
    else:
        if cbh.end <= t or t < cbh.start:
            return pd.NaT

    return ts.replace(hour=cbh.start.hour, minute=cbh.start.minute,
                      second=cbh.start.second,
                      microsecond=cbh.start.microsecond)


# assuming df looks similar to the one in the problem statement...
cbh = CustomBusinessHour(start='06:30', end='13:15',
                         weekmask='Mon Tue Wed Thu Fri')
df['session_start'] = df.index.map(lambda x: session_start(x, cbh))
df.dropna(how='all', subset=['session_start'], inplace=True)
df.set_index(['session_start', df.index], drop=True, inplace=True)

相关问题 更多 >