如何在pandas中筛选在两个事件之间发生过事件的用户?
我有一个表格,内容大致如下:
用户ID | 事件 | 时间戳 |
---|---|---|
1 | 启动 | 2023-09-15 14:31:44 |
1 | 购买 | 2023-09-15 14:31:49 |
1 | 取消 | 2023-09-15 14:31:50 |
1 | 添加 | 2023-09-15 14:31:52 |
2 | 添加 | 2023-09-16 14:31:40 |
2 | 取消 | 2023-09-16 14:31:44 |
2 | 启动 | 2023-09-16 14:31:49 |
2 | 购买 | 2023-09-16 14:31:50 |
2 | 购买 | 2023-09-16 14:31:52 |
3 | 购买 | 2023-09-17 14:31:44 |
3 | 取消 | 2023-09-17 14:31:49 |
3 | 移除 | 2023-09-17 14:31:50 |
3 | 添加 | 2023-09-17 14:31:52 |
我想筛选出那些在“购买”之后和“添加”之前有“取消”事件的用户(不管中间有没有其他事件)。
换句话说,我需要得到以下用户列表:
1, 3
谢谢你们的帮助
我试着添加了“购买时间戳”和“添加时间戳”这两列,然后像这样筛选数据:df[df.event == '取消'].query('时间戳 > '购买时间戳' & 时间戳 < '添加时间戳'')
但我在想,是否有更简单的方法来做到这一点。
1 个回答
2
代码
如果同一个用户的时间戳是按时间顺序排列的,就像示例数据框那样,你可以使用以下代码:
cond1 = df['event'].eq('buy').groupby(df['user_id']).cummax()
cond2 = df['event'].eq('add').groupby(df['user_id']).cummax()
out = df.loc[df['event'].where(cond1 & ~cond2).eq('cancel'), 'user_id'].unique()
输出
array([1, 3], dtype=int64)
示例代码
import pandas as pd
data = {'user_id': [1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3], 'event': ['launch', 'buy', 'cancel', 'add', 'add', 'cancel', 'launch', 'buy', 'buy', 'buy', 'cancel', 'remove', 'add'], 'timestamp': ['2023-09-15 14:31:44', '2023-09-15 14:31:49', '2023-09-15 14:31:50', '2023-09-15 14:31:52', '2023-09-16 14:31:40', '2023-09-16 14:31:44', '2023-09-16 14:31:49', '2023-09-16 14:31:50', '2023-09-16 14:31:52', '2023-09-17 14:31:44', '2023-09-17 14:31:49', '2023-09-17 14:31:50', '2023-09-17 14:31:52']}
df = pd.DataFrame(data)