基于排名条件创建Groupby列

2024-03-29 14:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python处理一个事件数据库,我需要编写一个函数来量化一个特定事件是否(在任何时候)跟随另一个特定事件。你知道吗

df = pd.DataFrame({'User':[1,1,1,2,2,2],
               'Product':['A','A','A','B','B','B'],
               'Updated_At':['2015-01-01',
                             '2015-02-01',
                             '2015-03-01',
                             '2015-04-01',
                             '2015-05-01',
                             '2015-06-01'],
                   'Event':[1,1,2,1,3,2]})

对于用户拥有的每个产品,事件2是否在下一次出现事件1之前的任何时间点跟随事件1。如果是,则保留event=1的行。你知道吗

答案('Event\u Updated'包含我要保留的行):

df = pd.DataFrame({'User':[1,1,1,2,2,2],
               'Product':['A','A','A','B','B','B'],
               'Updated_At':['2015-01-01',
                             '2015-02-01',
                             '2015-03-01',
                             '2015-04-01',
                             '2015-05-01',
                             '2015-06-01'],
               'Event':[1,1,2,1,3,2],
               'Updated_Event':['no', 'yes', 'no', 'yes', 'no', 'no']})

逻辑步骤似乎是继续使用groupby(['User','Product']),并创建一个虚拟列添加到groupby,然后检查在User,Product,EventType1的每个实例中是否也存在Event=2的行。类似于下面的“事件\虚拟”列:

df = pd.DataFrame({'User':[1,1,1,2,2,2],
               'Product':['A','A','A','B','B','B'],
               'Updated_At':['2015-01-01',
                             '2015-02-01',
                             '2015-03-01',
                             '2015-04-01',
                             '2015-05-01',
                             '2015-06-01'],
               'Event':[1,1,2,1,3,2],
               'Event_Dummy': [1,2,2,3,3,3],
               'Updated_Event':['no', 'yes', 'no', 'yes', 'no', 'no']})

那么这句话的大意是:

检查df.grouby('User','Product','Event_Dummy')是否包含2。你知道吗

请让我知道我能如何帮助澄清这个问题。你知道吗


Tags: 函数noevent数据库dataframedf事件product