在时间窗口内查找所有观察结果

时间:2018-06-11 14:01:09

标签: python pandas

我想在我的数据框中找到所有发生在彼此3分钟窗口内的特定商家的事件。这是一个最小的工作示例:

import pandas as pd
import numpy as np

merchant = ['A','A','A','A','A','B','B','B','B']
datetime = pd.to_datetime(([
            '2018-06-11 12:00:00',
            '2018-06-11 12:02:10',
            '2018-06-11 12:05:32',
            '2018-06-11 12:09:01',
            '2018-06-12 13:01:32',
            '2018-06-12 14:49:32',
            '2018-06-12 14:51:44',
            '2018-06-12 14:51:46',
            '2018-06-12 14:51:55'
        ]))

ID = range(1,10)


df = pd.DataFrame({'ID':ID,'datetime':datetime,'merchant':merchant})

df['unix_time'] = df.datetime.astype(np.int64)/10**9

Idf = df.merge(df, how = 'outer', on = ['merchant']).query('abs(unix_time_x - unix_time_y)<=3*60 and ID_x<ID_y')

Idf数据框包含我想要的结果:每一行都是一对ID,它们在3分钟之内在merchant处进行了转换。

    ID_x    datetime_x  merchant    ID_y    datetime_y
1   1   2018-06-11 12:00:00 A   2   2018-06-11 12:02:10
26  6   2018-06-12 14:49:32 B   7   2018-06-12 14:51:44
27  6   2018-06-12 14:49:32 B   8   2018-06-12 14:51:46
28  6   2018-06-12 14:49:32 B   9   2018-06-12 14:51:55
31  7   2018-06-12 14:51:44 B   8   2018-06-12 14:51:46
32  7   2018-06-12 14:51:44 B   9   2018-06-12 14:51:55
36  8   2018-06-12 14:51:46 B   9   2018-06-12 14:51:55

由于我只想要在同一商家发生的交易,我想我可以在groupby中做到这一点。我的实际数据要大得多,所以在我的示例中进行外连接和过滤是不可能的。

我可以执行与在groupby中显示的操作相同的操作吗?

0 个答案:

没有答案
相关问题