gpt4 book ai didi

python - pandas 及时交叉匹配事件

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

我有两个充满时间戳的pandasDataFrames。我想将这些事件交叉匹配到 5 天内。如果我要将 df1 交叉匹配到 df2,我希望大小为 len(df1) 的列表(一般意义上),其中每个元素包含 df1 中元素索引的列表,这些元素位于 df2 中相应元素的指定时间限制内。我还想要一个类似的结构,它包含事件之间的天数,而不是索引。

例如:

df1 = pd.DataFrame({'date_1': ['2016-10-10', '2016-10-11', '2016-10-18', '2016-10-29']})
df2 = pd.DataFrame({'date_2': ['2016-10-10', '2016-10-05', '2016-10-27', '2016-10-01']})

输出:

matched_indices = [[0,1], [0], [3], []]
matched_deltas = [[0,1], [5], [2], []]

有什么想法吗?

最佳答案

一种解决方案是迭代 df2 的所有行,并查找与 df1 中的日期的差异。

matched_indices = []
matched_deltas = []
# iterate throug hthe rows of df2
for index, row in df2.iterrows():
# s is a series that stores the difference between the two dates, the index is the same as df1's
s = abs((df1['date_1'] - row['date_2']).dt.days)
# keep only the differences that are less than 5
s = s.where(s<=5).dropna()
# add the indices to matched_index
matched_indices.append(list(s.index.values))
# add the values to matched_deltas
matched_deltas.append(list(s.values.astype(int)))

希望对您有帮助!

关于python - pandas 及时交叉匹配事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57114653/

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