【问题标题】:What does min(iterable, *[, key, default]) returnmin(iterable, *[, key, default]) 返回什么
【发布时间】:2021-05-18 22:02:31
【问题描述】:

对于下面的df,我想从当前Timestamp 之前和之后的10 个值的范围内,找到当前时间戳前一分钟的特定时间戳的最近日期时间。

但我观察到在不同情况下为 one_min_ago_data 返回了不同的值,有时它返回 Timestamp,有时它返回整个行作为 <class 'numpy.ndarray'>min(iterable, *[, key, default]) 返回什么?在这种情况下,min() 函数返回什么?我可能在这里忽略了一些东西,但我不确定是什么。任何建议表示赞赏。

df:

        Timestamp               A           B           C
912262  2001-02-10 00:01:45.910 45.5        NaN         zero
530129  2001-02-10 00:05:33.430 43.5        NaN         zero
243281  2001-02-10 00:07:05.600 45.0        NaN         zero
520580  2001-02-10 00:07:13.600 46.0        NaN         zero
228900  2001-02-10 00:07:23.600 47.0        NaN         zero

我使用的代码如下所示:

for i in range(1, len(df.index)):

    left_timestamp = df.loc[i - 10:i - 1]
    right_timestamp = df.loc[i + 1:i + 10]

    time_one_min_ago = df.loc[i, 'Timestamp'] - datetime.timedelta(minutes=1)

    one_min_ago_data = min(left_timestamp.append(right_timestamp).to_numpy(), key=lambda x: abs(x[timestamp_index] - time_one_min_ago))

【问题讨论】:

    标签: python arrays pandas for-loop min


    【解决方案1】:

    我认为 pandas 的滚动窗口非常适合这个,但它有太多限制,所以我们回到了一些好的旧循环:

    timestamp = df['Timestamp'].to_numpy()
    l = len(timestamp)
    win_size = 10
    
    result = np.empty(l, dtype='datetime64[ns]')
    
    for i, ts in enumerate(timestamp):
        # Take 10 rows from above and 10 from below, but not the current row
        lbound = max(i-win_size, 0)
        ubound = min(i+win_size, l-1) + 1
        tmp = timestamp.take([idx for idx in range(lbound, ubound) if idx != i])
        
        # Find the timestamp with the lowest distance from the current timestamp
        argmin = np.abs(tmp - ts).argmin()
        result[i] = tmp[argmin]
        
    df['result'] = result
    

    【讨论】:

    • 您好,感谢您的解决方案,您知道我如何获取与tmp 对应的A 值吗?我想算出他们的意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2016-01-20
    • 2013-09-01
    • 2017-08-25
    • 2021-07-05
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多