gpt4 book ai didi

python - 在 Pandas 时间序列中,如何为每一行获取延迟到期前的最后一个值?

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:08 27 4
gpt4 key购买 nike

我在 Pandas 中有一个具有单个值 A 的时间序列。我想生成第二列 B,其中包含某个延迟(相对于原始行的时间)到期之前的最后一个值。这些行没有恒定的时间差。有没有办法在 Pandas(或 Numpy)中有效地实现这一点?数据框可能包含数百万行,我希望这个操作最多只需要几秒钟。

这是一个例子:

time  A
10:00 10
11:00 20
11:05 30
11:15 20

设延迟为 10 分钟。那么结果应该是:

time  A  B
10:00 10 10 # In 10 minutes the value is still the same
11:00 20 30 # In 5 < 10 minutes, the value will have changed
11:05 30 30 # Exactly, not less than 10 minutes
11:15 20 20 # Last row contains the same value

编辑:如果没有快速的 Pandas/Numpy 解决方案,我将只在 Numba 中编写代码。然而,出于某种原因,我过去对类似问题的 Numba 解决方案(nopython & nested for & break)相当慢,这就是为什么我要求更好的方法。

最佳答案

这是一种方法。关键是 searchsorted 函数,它找到延迟时间值的插入索引:

import numpy as np
import pandas as pd

df = pd.DataFrame({'time': ['10:00', '11:00', '11:05', '11:15'],
'A': [10, 20, 30, 20]})
df['time'] = pd.to_timedelta(df['time'] + ':00')
t2 = df['time'] + pd.to_timedelta('10min')
idx = df['time'].searchsorted(t2)
df['B'] = df.iloc[idx - 1]['A'].values
print(df)
# time A B
# 0 10:00:00 10 10
# 1 11:00:00 20 30
# 2 11:05:00 30 30
# 3 11:15:00 20 20

关于python - 在 Pandas 时间序列中,如何为每一行获取延迟到期前的最后一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376944/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com