在给定日期时间之前查找列表中的最新日期时间

时间:2015-10-14 23:51:48

标签: python datetime numpy pandas timestamp

我有两个np.datetime64格式的日期时间列表。 (没必要 - 可以是unix时间戳或datetime.datetime

当我遍历密集列表(times_dense)时,我希望从times_sparse得到的时间最接近times_dense但不到datetime的时间。我most_recent_time = None for time_d in times_dense: for time_s in times_sparse: # time_d is after time_s and time_s is after most_recent_time if(time_d >= time_s and time_s > most_recent_time): most_recent_time = time_s return most_recent_time 很可怕,所以我就把它扔到了一起。

[self->detectBeacons allValues]

有一种简单的方法吗?我的方法会起作用吗?它很笨重,运行时间很长。什么是解决这个问题的最佳方法?

PS。我最初在熊猫数据框中有这些,但是因为我无法在数据框中找到解决方案而取出它们。如果这可以与熊猫一起使用,那就更好了。

1 个答案:

答案 0 :(得分:1)

以下是您描述的时间比较。现在我专注于重建你的情况,而不是让它变得最佳

制作两个日期数组:

In [434]: t1=np.array(np.random.randint(100,size=(10,)),dtype='datetime64[D]')

In [435]: t2=np.array(np.random.randint(100,size=(10,)),dtype='datetime64[D]')

In [436]: t1
Out[436]: 
array(['1970-02-25', '1970-01-31', '1970-01-04', '1970-03-17',
       '1970-03-17', '1970-01-02', '1970-02-09', '1970-04-05',
       '1970-02-22', '1970-03-08'], dtype='datetime64[D]')

In [437]: t2
Out[437]: 
array(['1970-01-16', '1970-02-24', '1970-02-28', '1970-01-21',
       '1970-03-08', '1970-03-22', '1970-02-02', '1970-02-12',
       '1970-02-24', '1970-02-06'], dtype='datetime64[D]')

开始日期:

In [438]: recent=np.datetime64(0,'D')

In [439]: recent
Out[439]: numpy.datetime64('1970-01-01')

你的迭代:

In [440]: for td in t1:
    for ts in t2:
        if (td>=ts) and (ts>recent):
            recent=ts
   .....:             

In [441]: recent
Out[441]: numpy.datetime64('1970-03-22')

np.datetime64可以很好地处理比较(和算术)。

具有np.array值的

np.datetime64可以与具有整数值的数组一样使用

(对于不同的t2):

In [458]: t2.max()
Out[458]: numpy.datetime64('1970-04-05')

In [459]: t2[np.argmax(t1>=t2[:,None],axis=0)]
Out[459]: 
array(['1970-02-08', '1970-03-07', '1970-03-07', '1970-03-07',
       '1970-03-07', '1970-03-07', '1970-02-08', '1970-03-07',
       '1970-02-08', '1970-03-07'], dtype='datetime64[D]')

像这样的表达式最后一个可能会重现你的迭代 - 但它需要调整。