gpt4 book ai didi

python - 找到具有正时间增量的数据帧之间最近的行

转载 作者:太空狗 更新时间:2023-10-30 02:53:37 24 4
gpt4 key购买 nike

我有两个 dataframes,每个都有一个 datetime 列:

df_long=
mytime_long
0 00:00:01 1/10/2013
1 00:00:05 1/10/2013
2 00:00:55 1/10/2013

df_short=
mytime_short
0 00:00:02 1/10/2013
1 00:00:03 1/10/2013
2 00:00:06 1/10/2013

时间戳是唯一的,可以假定在两个数据帧中的每一个中都排序了。

我想创建一个新数据框,其中包含 mytime_short 中最近的 (index,mytime_long) 之后或同时值(因此具有非负时间增量)

ex.
0 (0, 00:00:02 1/10/2013)
1 (2, 00:00:06 1/10/2013)
2 (np.nan,np.nat)

最佳答案

写一个函数在给定时间戳的情况下获取 df_short 中最接近的索引和时间戳

def get_closest(n):
mask = df_short.mytime_short >= n
ids = np.where(mask)[0]
if ids.size > 0:
return ids[0], df_short.mytime_short[ids[0]]
else:
return np.nan, np.nan

df_long.mytime_long 上应用此函数,以在元组中获取包含索引和时间戳值的新数据帧

df = df_long.mytime_long.apply(get_closest)
df
# output:
0 (0, 2013-01-10 00:00:02)
1 (2, 2013-01-10 00:00:06)
2 (nan, nan)

ilia timofeev 的回答让我想起了这个pandas.merge_asof function这非常适合这种类型的连接

df = pd.merge_asof(df_long, 
df_short.reset_index(),
left_on='mytime_long',
right_on='mytime_short',
direction='forward')[['index', 'mytime_short']]
df
# output:
index mytime_short
0 0.0 2013-01-10 00:00:02
1 2.0 2013-01-10 00:00:06
2 NaN NaT

关于python - 找到具有正时间增量的数据帧之间最近的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48871617/

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