首页 > 解决方案 > 如何在 Pandas 中复制 Excel 的 countifs 功能

问题描述

我正在尝试添加一个“月度订单”列,该列计算具有特定 ID 的客户在特定 CohortDate 内进行了多少次交易。

基本上,它是一个 COUNTIFS 函数,其中 RANGES 都是 IDS,所有 CohortDate 都等于任何给定行的 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

标签: pythonpandasdataframe

解决方案


要按某些变量进行分组,我们可以使用将transformgroupby 应用于一个系列而不是返回一个新的数据帧。

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

推荐阅读