python - 如何在 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
解决方案
要按某些变量进行分组,我们可以使用将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
推荐阅读
- reactjs - 提交值时如何在 React 挂钩中使用回调函数?
- twilio - 我可以使用 Authy 在 SMS 和电子邮件中发送相同的 OTP 吗?
- java - 增加recyclerview中特定项目的项目计数
- json - 在 vb.net 中读取 JSON 字符串
- reactjs - 如何显示/隐藏反应钩子的一个结果
- python - 导入模块:函数内的全局变量
- django - 字典的键值没有显示在 html 中由 django
- docker - docker登录到托管存储库nexus失败
- angular - 如何给formio表单提供虚拟值
- javascript - 当你从基于类切换到基于函数的 React 组件时,公共方法的替代方案是什么?