是否可以用numpy向量化替换此熊猫中的嵌套循环以加快代码处理速度?

时间:2020-06-16 13:25:19

标签: python pandas numpy vectorization

数据:

orderid         shopid  userid      event_time            timestamp 
31077182438530  10151   154282716   2019-12-27 00:33:02   1577406782    
31078679118082  10151   154282716   2019-12-27 00:58:00   1577408280    
31079250834942  10151   154282716   2019-12-27 01:07:30   1577408850    
31086252001110  10151   12825914    2019-12-27 03:04:12   1577415852    
31087365203493  10151   102963110   2019-12-27 03:22:46   1577416966    

当前代码:

shopid = df.shopid.values
userid = df.userid.values
event_time = df.timestamp.values
flag = np.zeros(shopid.shape, dtype=int)

current_shop = 0
for i in range(len(df)):
    if shopid[i] != current_shop:
        current_shop = shopid[i]
        prev_time = event_time[i] - 3600
        users = {userid[i]: 1}
    for j in range(i+1, len(df)):
        if (current_shop == shopid[j]) and (event_time[j] - event_time[i] <= 3600):
            if userid[j] not in users:
                users[userid[j]] = 0
            users[userid[j]] += 1
        else:
            break
    while j - i / len(users) < 3 and event_time[j-1] - prev_time > 3600:
        j -= 1
        users[userid[j]] -= 1
        if users[userid[j]] == 0:
            users.pop(userid[j])
    if j - i / len(users) >= 3:
        flag[i:j] = 1
    prev_time = event_time[i]    

基本上,我想为每个商店做的事,找出哪个用户在任何间隔的1小时内做出了3个或更多的订单。因此,在上面,我遍历每个商店(第一个循环),然后遍历每个商店的订单(第二个循环),检查时间是否在1小时以内,然后将用户添加到包含订单数的字典中。之后,我执行一个递减循环(第3循环)以计算订单数/唯一用户,如果少于3,我将把用户从字典中弹出。最后,检查条件是否相反,如果有效,我将标志设置为1。然后使用该标志标识特定的订单ID,相应的商店和用户ID。

预期输出:

orderid         shopid  userid      event_time            timestamp     flag
31077182438530  10151   154282716   2019-12-27 00:33:02   1577406782    1
31078679118082  10151   154282716   2019-12-27 00:58:00   1577408280    1
31079250834942  10151   154282716   2019-12-27 01:07:30   1577408850    1
31086252001110  10151   12825914    2019-12-27 03:04:12   1577415852    0
31087365203493  10151   102963110   2019-12-27 03:22:46   1577416966    0

1 个答案:

答案 0 :(得分:0)

你可以试试吗?

df['event_time'] = pd.to_datetime(df['event_time'])

这应该为您提供每个商店每小时的计数

df.groupby(['shopid','userid', pd.Grouper(key='event_time',freq='H')]).count()

df['flag'] = df.groupby(['shopid','userid', pd.Grouper(key='event_time',freq='H')])['userid'].count().values

这是我得到的输出

shopid  userid  event_time  orderid timestamp
0   10151   12825914    2019-12-27 03:00:00 1   1
1   10151   12825914    2019-12-27 07:00:00 1   1
2   10151   102963110   2019-12-27 03:00:00 1   1
3   10151   102963110   2019-12-27 04:00:00 1   1
4   10151   154282716   2019-12-27 00:00:00 2   2
5   10151   154282716   2019-12-27 01:00:00 1   1
6   10151   154282716   2019-12-27 03:00:00 1   1
7   10151   154282716   2019-12-27 04:00:00 1   1
8   10151   154282716   2019-12-27 14:00:00 1   1