【问题标题】:pandas cross matching events in timepandas 及时交叉匹配事件
【发布时间】:2019-07-19 14:34:01
【问题描述】:

我有两只熊猫DataFrames,里面装满了Timestamps。我想在 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], []]

有什么想法吗?

【问题讨论】:

  • 如果你要包含代码(一件好事),至少粘贴你实际运行过的代码。
  • 祝你好运呵呵:-)
  • @WeNYoBen 太傻了。我已经纠正了你故意犯的错误!无论如何,感谢您的初步帮助
  • @piRSquared 点现在可以随意运行代码。现在,你能取消你的反对票吗?我认为这是一个有趣的问题,如果最初提出的问题。

标签: python pandas


【解决方案1】:

一种解决方案是遍历 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)))

希望对你有帮助!

【讨论】:

    【解决方案2】:
    s = np.abs(df1.date_1.values[:,None]-df2.date_2.values)/np.timedelta64(60*60*24, 's')
    newdf=pd.DataFrame(s)
    matched_deltas = 
    newdf.mask(newdf>5).stack().groupby(level=1).apply(list).reindex(df1.index).tolist()
    matched_deltas
    
    matched_indices =newdf.mask(newdf>5).stack().reset_index().groupby('level_1')['level_0'].apply(list).reindex(df1.index).tolist()
    matched_indices
    

    输出:

    [[0.0, 1.0], [5.0], [2.0], nan]
    [[0, 1], [0], [3], nan]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      相关资源
      最近更新 更多