1

我有一个看起来像这样的 pd.dataframe:

cookie     date           channel       goal_reached
cookie_1   2020-01-12     paid          0
cookie_1   2020-02-17     organic       0
cookie_1   2020-04-02     referral      1
cookie_1   2020-05-13     direct        0
cookie_1   2020-05-16     direct        0
cookie_2   2020-01-18     referral      0
cookie_2   2020-03-13     paid          1
cookie_2   2020-04-01     organic       0
cookie_2   2020-05-16     organic       0
cookie_2   2020-05-22     paid          0
cookie_3   2020-01-13     direct        0
cookie_3   2020-04-14     organic       0
cookie_3   2020-06-10     organic       0

我想对每个 cookie 值进行分组,并删除目标到达值为 1 的日期之后的所有行。如果 cookie 没有目标到达值 1,我需要获取所有行。

我想要这样的最终输出:

cookie     channel                         goal_reached
cookie_1   paid > organic > referral       1
cookie_2   referral > paid                 1
cookie_3   direct > organic > organic      0

我有以下代码,但它可以按所有行分组:

df = df.sort_values(['cookie', 'date'],
                    ascending=[False, True])
df = df.groupby('cookie', as_index=False).agg({'channel': lambda x: "%s" % ' > '.join(x), 'reg_goal': 'max'})
4

1 回答 1

0

你可以试试这个:

df = df[df.groupby('cookie')['goal_reached'].transform(lambda x: x.cumsum().cumsum()).lt(2)]
df = df.groupby('cookie').agg({'channel': lambda x: ' > '.join(x), 'goal_reached': 'max'})
print(df)

                             channel  goal_reached
cookie                                            
cookie_1   paid > organic > referral             1
cookie_2             referral > paid             1
cookie_3  direct > organic > organic             0
于 2020-07-28T14:29:49.740 回答