gpt4 book ai didi

python - 如何在 Pandas 中复制 Excel 的 countifs 功能

转载 作者:行者123 更新时间:2023-12-01 00:40:27 25 4
gpt4 key购买 nike

我正在尝试添加一个“每月订单”列,该列计算具有特定 ID 的客户在特定群组日期内的交易数量。

基本上,它是一个 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

最佳答案

要按某些变量进行分组,我们可以使用 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

关于python - 如何在 Pandas 中复制 Excel 的 countifs 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57384303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com