Python 获取上一个事务日期的列值

Python 获取上一个事务日期的列值,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我想获得客户在上次交易日期使用和购买的折扣代码和产品变体 对于date,我可以使用.groupby('customer\u name')['day'].max().reset\u index() 预期产出: customer date discount_code product_variant 0 KATIE 2019-05-15 no_discount X1.1 1 KATIE 2019-05-15 no_discount

我想获得客户在上次交易日期使用和购买的折扣代码和产品变体

对于date,我可以使用
.groupby('customer\u name')['day'].max().reset\u index()

预期产出:

     customer  date      discount_code product_variant
0    KATIE  2019-05-15  no_discount        X1.1
1    KATIE  2019-05-15  no_discount        X1.2
15   KATIE  2019-06-24  no_discount        X1.1
16   KATIE  2019-06-24  no_discount        X2
141  MAX    2019-11-26  PR19               X1.1
263  OPRAH  2019-12-01  PR19               X1.2
264  OPRAH  2019-12-01  PR19               X2
334  PAUL   2020-01-14  no_discount        X3
1247 PAUL   2019-10-30  CHRISTMAS19        X2

IIUC您可以
groupby
转换每个客户的最新日期,然后比较并获取另一个
groupby
的最新日期:

     customer  date      discount_code product_variant
15   KATIE  2019-06-24  no_discount        X1.1, X2
141  MAX    2019-11-26  PR19               X1.1
263  OPRAH  2019-12-01  PR19               X1.2, X2
334  PAUL   2020-01-14  no_discount        X3
s = df.groupby("customer")["date"].transform("max")

print (df[df["date"].eq(s)].groupby("customer").agg(lambda d: ", ".join(d.unique())))

                date discount_code product_variant
customer                                          
KATIE     2019-06-24   no_discount        X1.1, X2
MAX       2019-11-26          PR19            X1.1
OPRAH     2019-12-01          PR19        X1.2, X2
PAUL      2020-01-14   no_discount              X3