【问题标题】:Finding most recent datetime in list before a given datetime在给定日期时间之前的列表中查找最近的日期时间
【发布时间】:2016-01-13 06:22:17
【问题描述】:

我有两个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

有没有简单的方法来做到这一点?我的方法会奏效吗?它很笨重并且运行时间很长。解决这个问题的最佳方法是什么?

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

【问题讨论】:

  • times_dense 和 times_sparse 到底是什么? Python 列表、numpy 数组、scipy 稀疏矩阵或您自己制作的一些可迭代对象?
  • 现在两者都是 np 数组。但它们可以是列表或 pandas 数据框中。
  • most_recent_time 的重要性是什么?此外,当您说您希望 time_sparse 中最接近 time_dense 的时间时,您是针对 time_dense 中的特定给定元素,还是希望找到一对时间元素,一个在 time_sparse 中,另一个在 time_dense 中,它们具有最小值与其他可能的对相比的距离?
  • most_recent_time 看起来就像一个临时值,用于迭代地找到最大值(或最小值)。

标签: python datetime numpy pandas timestamp


【解决方案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]')

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

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 1970-01-01
    • 2015-02-08
    • 2021-07-19
    • 1970-01-01
    • 2021-01-07
    • 2018-07-26
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多