gpt4 book ai didi

python - 查找具有与 id 匹配的最近时间戳的行,并添加具有值的行

转载 作者:行者123 更新时间:2023-12-04 13:30:31 25 4
gpt4 key购买 nike

我有 2 个数据帧,并且想根据最近的日期时间和匹配的 ID 将一行插入到 df1 中,其中的值来自 df2。示例 df 如下:

df1
storeID datetime
0 111 2020-01-01 00:50:00
1 222 2020-01-05 05:00:00
2 333 2020-01-10 10:00:00

df2
storeID datetime Value
0 111 2020-01-01 00:55:00 1
1 111 2020-01-05 01:00:00 2
2 222 2020-01-10 05:50:00 3
3 222 2020-01-15 04:55:00 4
4 333 2020-01-20 10:10:00 5
5 333 2020-01-20 11:00:00 6
输出应该是这样的:
df1
storeID datetime Value
0 111 2020-01-01 00:50:00 1
1 222 2020-01-05 05:00:00 4
2 333 2020-01-10 10:00:00 5
我遇到了 this question ,这是非常相似的,但是,它没有考虑 ID 应该匹配。在实际示例中,df1 有 50.000+ 行,df2 有 200.000+ 行。

最佳答案

合并并不完全是解决这个问题的方法。使用 merge_asof :

pd.merge_asof(df1,df2,on='datetime', by='storeID', direction='nearest')
输出:
   storeID            datetime  Value
0 111 2020-01-01 00:50:00 1
1 222 2020-01-05 05:00:00 3
2 333 2020-01-10 10:00:00 5

关于python - 查找具有与 id 匹配的最近时间戳的行,并添加具有值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65360176/

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