【问题标题】:Getting the latest day without a record containing that date获取没有包含该日期的记录的最新日期
【发布时间】:2015-12-06 18:05:33
【问题描述】:

我正在尝试构建一个显示时间表列表的视图,每个时间表都有“可用性”插槽,其中包含一个from_datetime 和一个to_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。我想要一个快速退货的方法。我目前有一个实现,我遍历所有(有序)插槽以获得时间表,等到我找到一个空的日子并在那天之前返回插槽。但是,目前这非常缓慢。还有其他想法吗?

【问题讨论】:

    标签: python django datetime django-queryset


    【解决方案1】:

    也许在测试列上对数据框进行切片,然后在索引上应用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多