gpt4 book ai didi

python - 根据最近的日期时间比较值

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:31 25 4
gpt4 key购买 nike

我有两个 pandas 数据框,都有两列:日期时间和值( float )。我想根据最近的日期时间从数据帧 B 的值中减去数据帧 A 的值。

例子:

dataframe A:
datetime | value
01-01-2016 00:00 | 10
01-01-2016 01:00 | 12
01-01-2016 02:00 | 14
01-01-2016 03:00 | 12
01-01-2016 04:00 | 12
01-01-2016 05:00 | 16
01-01-2016 06:00 | 18


dataframe B:
datetime | value
01-01-2016 00:20 | 5
01-01-2016 00:50 | -5
01-01-2016 01:20 | 12
01-01-2016 01:50 | 30
01-01-2016 02:20 | 1
01-01-2016 02:50 | 6
01-01-2016 03:50 | 0

如果是 A 的第一行,这意味着 B 的最近日期时间也将是第一行,因此:10-5 = 5。如果是 A 的第四行 (01-01-2016 3:00) 这意味着 B 的第六行最近,差值为:12-6 = 6。

我目前使用 for 循环执行此操作:

for i, row in data.iterrows():
# i is the index, a Timestamp
data['h'][i] = row['h'] - baro.iloc[baro.index.get_loc(i,method='nearest')]['h']

它工作正常,但是否可以更快地执行此操作?

最佳答案

pandas 0.19 的新功能 pd.merge_asof

pd.merge_asof(dfa, dfb, 'datetime')

enter image description here

关于python - 根据最近的日期时间比较值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40468656/

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