python - 非常棘手的加入 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 中可行吗?
解决方案
是的,我们有一个方法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
推荐阅读
- vba - 访问辅助电子邮件帐户中的子文件夹
- wordpress - 当我将 html 转换为 wordpress 时,图像不加载
- git - VS Code 尝试推送到已删除的存储库
- javascript - navigator.deviceMemory 在远程网络服务器上未定义,但在 .html 文件中使用时有效
- kotlin - 让 ObjectBox 与 LiveData 和 Kotlin 一起工作
- react-native - 为什么 renderCamera 不再调用
- oauth-2.0 - 我应该在 google oauth2 中为多个客户端独立存储访问和刷新令牌吗?
- javascript - 如何拆分正则表达式匹配
- c# - 无效的 JWT 签名
- botframework - 如何从用户话语中纠正 LUIS.AI 应用程序中的拼写错误?使用 Bing 拼写检查器 api 或在意图中标记拼写错误的单词