获取没有包含该d的记录的最近一天

2024-04-19 10:28:48 发布

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

我正在尝试构建一个视图来显示时间表列表,每个时间表都有一个包含from_datetimeto_datetime的“可用性”插槽。我试图找到最新的'可用性'插槽与第一个插槽之间没有空的日子。例如:

Date   Has availability slot
1/1    Yes
2/1    Yes
3/1    Yes <---- This is the date I'd like to return
4/1    No
5/1    Yes
6/1    Yes
7/1    No

之前我只是在每个时间表上注释可用性槽的Max,但在本例中会返回7/1。我想要一个快速归还的方法。我目前有一个实现,在这个实现中,我遍历所有(已排序的)时间段来获得一个时间表,等到找到一个空的一天,然后在这一天之前返回这个时间段。然而,目前这是非常缓慢的。还有其他想法吗?你知道吗


Tags: tonofrom视图列表datetimedate时间表
1条回答
网友
1楼 · 发布于 2024-04-19 10:28:48

也许在测试列上切片数据帧,然后在索引上应用min来获得第一个空槽?你知道吗

    import pandas as pd
    import random

    index = pd.date_range('01/01/2005', periods = 12, freq = 'A')
    #to get a random list with booleans
    data = [True] + [bool(random.getrandbits(1)) for x in range(11)] 
    df = pd.DataFrame(data, index  = index, columns = ['Test'])
    #finds the first non True slot and gets all the previous items
    result = df.loc[:min(df[df.Test == False].index)].ix[:-1,:]
    print df, result

                Test
    2005-12-31  True
    2006-12-31  True
    2007-12-31  True
    2008-12-31  True
    2009-12-31  False
    2010-12-31  True
    2011-12-31  True
    2012-12-31  True
    2013-12-31  True
    2014-12-31  False
    2015-12-31  False
    2016-12-31  True

                Test
    2005-12-31  True
    2006-12-31  True
    2007-12-31  True
    2008-12-31  True

相关问题 更多 >