首页 > 解决方案 > 非常棘手的加入 python/pandas - 归因建模相关

问题描述

我有 2 张表:一张带有购买和时间戳,一张带有事件和时间戳。

Table1: 

user_id  | purchase_revenue | time_stamp 

1  |  10.0        |      07.10.2019
1  |  20.0        |      09.10.2019 


Table2: 

user_id | event_id  | time_stamp 

1  | 1    |     05.10.2019
1  | 2    |     06.10.2019
1  | 3    |     07.10.2019
1  | 2    |     08.10.2019
1  | 3    |     09.10.2019

我想以这样一种方式加入他们,即我想收集仅与该购买相关的事件。例如:在上述情况下。结果连接将是:

Joined_table:

User_id | purchase_revenue | event_id | event_order
1       | 10               |   1      |    1
1       | 10               |   2      |    2
1       | 10               |   3      |    3
1       | 20               |   2      |    1
1       | 20               |   3      |    2

因此,事件 1、2 和 3 获得购买 10.0 的信用,事件 2 和 3 获得购买 20.0 的信用。

这在 Python 中可行吗?

标签: pythonpandas

解决方案


是的,我们有一个方法merge_asof

df1.time_stamp = pd.to_datetime(df1.time_stamp,dayfirst=True)
df2.time_stamp = pd.to_datetime(df2.time_stamp,dayfirst=True)
out = pd.merge_asof(df2,df1,by='user_id',on='time_stamp',direction = 'forward')
out['event_order']=out.groupby(['user_id','purchase_revenue']).cumcount()+1

out

Out[527]: 
   user_id  event_id time_stamp  purchase_revenue  event_order
0        1         1 2019-10-05              10.0            1
1        1         2 2019-10-06              10.0            2
2        1         3 2019-10-07              10.0            3
3        1         2 2019-10-08              20.0            1
4        1         3 2019-10-09              20.0            2

推荐阅读