所以我有两个数据框。 activity_log 根据客户端的client_id 记录客户端登录的时间。如果客户端在一段时间内多次登录,则 client_id 可能会出现多次。
我需要在此 activity_log 中创建第三列,以查找创建客户端的日期。这个 created_date 是通过查看 user_table 中最早的 user_created 日期计算出来的。
事件日志
用户表
我试过使用 pandas merge
activity_log.merge(client_table[['client_id','user_created']], how='inner', on='client_id')
这个问题是我最终得到一个比原始 activity_log 更大的表,因为 client_id 在 activity_log 中出现多次,在 user_table 中出现多次。
我想在 user_table 中查找 client_id,获取最早的 user_created 值并将其放入 activity_log 中的 created_date 列。
关于实现此目标我还需要做什么的任何想法?
最佳答案
听起来你想从 usr_df
中获取最早的事件,你可以在按日期排序后使用 groupby
和 first
来做到这一点:
df1 = usr_df.sort_values('user_created', ascending = True).groupby('client_id').first()
df1
看起来像这样:
user_id user_created
client_id
1 asasdsa2 2021-10-12
2 3asdasd21 2021-11-12
3 1asdsaa22 2021-02-12
现在您可以将 act_df 与这个合并:
act_df.merge(df1, on = 'client_id')
输出:
client_id activity_date user_id user_created
-- ----------- --------------- --------- -------------------
0 1 12/12/2022 asasdsa2 2021-10-12 00:00:00
1 1 11/12/2022 asasdsa2 2021-10-12 00:00:00
2 1 9/12/2022 asasdsa2 2021-10-12 00:00:00
3 1 8/12/2022 asasdsa2 2021-10-12 00:00:00
4 2 12/12/2022 3asdasd21 2021-11-12 00:00:00
5 2 11/12/2022 3asdasd21 2021-11-12 00:00:00
6 3 10/12/2022 1asdsaa22 2021-02-12 00:00:00
7 3 9/12/2022 1asdsaa22 2021-02-12 00:00:00
关于python - 无需合并的 Pandas 索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70955138/