python - Get column values on last transaction date
问题描述
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
I want to get the discount code and product variant that customers used and bought on their last transaction date.
With date, I can use .groupby('customer_name')['day'].max().reset_index()
.
Expected Output:
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
解决方案
IIUC you can groupby
and transform
for latest date of each customer, and then compare and get latest date for another groupby
:
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
推荐阅读
- c++ - 如何创建对 CodeQL 的导入
- node.js - **已解决** discord.js guildMemberAdd() 未向对象添加正确的值
- ios - 如何将来自 iOS 应用程序的 api 调用转发到端口 443 到 Nginx 中的另一个 SSL 端口?
- python - 如果列值包含字典键,则用字典值填充其他列值
- python - 将预训练的 Keras 加载到 Sagemaker - 本地分类有效,但 sagemaker 分类发生变化
- bash - 为什么 bash 不解释传递的参数?
- c++ - 用户输入与赋值输入具有不同的输出,尽管它们都具有相同的值
- r - 使用 R 使用来自单独 df 的信息有条件地填充数据帧值
- mysql - 使用个人最佳记录创建 SQL 视图
- pandas - 在数据框中按行聚合特征