如何在Pandas中复制excel的功能

2024-09-30 20:36:16 发布

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

我正在尝试添加一个“每月订单”列,该列计算具有特定id的客户在特定的CohortDate中有多少笔交易

基本上,它是一个COUNTIFS函数,其中范围是所有ID和所有CohortDates等于任何给定行的ID和CohortDate

非常感谢您的帮助

import pandas as pd
import numpy as np

df = pd.DataFrame({'order_id': [75054,75057,75059,75061,75066],
                   'customer_id': [101692,101694,101734,101692,101694],
                   'CohortDate': ['2016-05','2016-05','2016-05','2016-05','2016-06'] 
                  })

我希望得到的结果如下:

order_id    customer_id    CohortDate    Monthly_orders

75054    101692    '2016-05'    2

75057    101694    '2016-05'    1

75059    101734    '2016-05'    1

75061    101692    '2016-05'    2

75066    101694    '2016-06'    1

Tags: 函数订单importidpandas客户asorder
1条回答
网友
1楼 · 发布于 2024-09-30 20:36:16

为了按某些变量分组,我们可以使用transform,它将groupby应用于一个系列,而不是返回一个新的数据帧

df.groupby(['customer_id','CohortDate'])['customer_id'].transform('count')

这将返回原始数据帧的计数

order_id    customer_id CohortDate  count
0   75054   101692  2016-05 2
1   75057   101694  2016-05 1
2   75059   101734  2016-05 1
3   75061   101692  2016-05 2
4   75066   101694  2016-06 1

相关问题 更多 >