为了账号安全,请及时绑定邮箱和手机立即绑定

根据 groupby 条件过滤前 n 行

根据 groupby 条件过滤前 n 行

白猪掌柜的 2021-12-17 16:44:41
我有一个包含 4 列 User_id、Transaction_id、product 和 datetime 的数据框。对于每个用户,我必须选择他最近的前 n 笔交易,假设 n=2,我的数据框如下:    transaction_id  user_id  product  date         T1             U1     P1     2019-03-27         T1             U1     P2     2019-03-27         T1             U1     P3     2019-03-27         T2             U1     P2     2019-03-21         T2             U1     P3     2019-03-21         T3             U1     P2     2019-03-20我试图通过 Pandas 数据框帮助该组并在每个组中选择最新的来做到这一点我期望的输出是:   transaction_id   user_id  product  date        T1            U1       P1     2019-03-27        T1            U1       P2     2019-03-27        T1            U1       P3     2019-03-27        T2            U1       P2     2019-03-21        T2            U1       P3     2019-03-21
查看完整描述

1 回答

?
富国沪深

TA贡献1790条经验 获得超9个赞

想法是首先删除重复项DataFrame.drop_duplicates,获取每组和DataFrame.merge原始数据帧的top2 值:


df = (df.merge(df.drop_duplicates(['user_id','date'])

                 .sort_values('date',ascending = False)

                 .groupby('user_id')

                 .head(2)[['user_id','date']])

       )

print (df)

  transaction_id user_id product       date

0             T1      U1      P1 2019-03-27

1             T1      U1      P2 2019-03-27

2             T1      U1      P3 2019-03-27

3             T2      U1      P2 2019-03-21

4             T2      U1      P3 2019-03-21


查看完整回答
反对 回复 2021-12-17
  • 1 回答
  • 0 关注
  • 122 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信