簡體   English   中英

pandas:分組並從表中查找最近的事件,然后加入現有的表?

[英]pandas: group and find most recent event from table, then join with existing table?

我在pandas中有兩個表,一個user表和一個history表 - 后者基本上是用戶采取的所有操作的日志。

用戶表:

   |  user_id  |  source
0  |  1        |  blog
1  |  2        |  blog
2  |  3        |  organic

歷史表:

   |  user_id  |  action_type  |  t_actioned
0  |  1        |  332          |  2018-08-04 12:35:23   
1  |  1        |  453          |  2018-08-04 12:36:23   
2  |  1        |  332          |  2018-08-04 12:38:23   
3  |  2        |  452          |  2018-08-04 12:40:23   
4  |  3        |  523          |  2018-08-04 12:41:23   
5  |  2        |  452          |  2018-08-04 12:41:43   

我想從history表中找到每個用戶采取的最新操作的時間戳,並將其作為新列添加到user表中。

我怎樣才能做到這一點?

看看這個答案 ,我認為它是這樣的:

 # Get the latest action by user
 first_action = history.group_by('user_id').agg(lambda df: df.sort('t_actioned')[-1:].values[0])
 user.first_action = # join with first_action somehow?

但是agg查詢對我不起作用,我不知道下一步該做什么。

首先排序,刪除重復項並從歷史數據框中創建一個系列:

s = history.sort_values('t_actioned', ascending=False)\
           .drop_duplicates('user_id')\
           .set_index('user_id')['action_type']

然后將其映射到您的用戶數據框:

user['action_type'] = user['user_id'].map(s)

正如在評論中指出,如果你的日志已經排序,就能避免sort_values和使用drop_duplicates('user_id', keep='last')

您可以利用以下事實:在構建具有多個重復鍵的字典時,您將只保留最后一個鍵。

m = dict(history.sort_values('t_actioned').pipe(
    lambda d: zip(d.user_id, d.t_actioned)))

user.assign(latest=user.user_id.map(m))

   user_id   source               latest
0        1     blog  2018-08-04 12:38:23
1        2     blog  2018-08-04 12:41:43
2        3  organic  2018-08-04 12:41:23

考慮數據的短版本已經按't_actioned'排序

user.assign(latest=user.user_id.map(dict(zip(history.user_id, history.t_actioned))))

其他方式:

history = history.groupby(['user_id']).apply(lambda x: x.sort_values('t_actioned', ascending = False))
history = history.drop_duplicates(subset = ['user_id'], keep = 'first')
user = pd.merge(user, history[['t_actioned']], on = 'user_id', how = 'left')

輸出:

   user_id   source          t_actioned
0        1     blog 2018-08-04 12:38:23
1        2     blog 2018-08-04 12:41:43
2        3  organic 2018-08-04 12:41:23

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM