pandas - GroupBy 唯一聚合并在熊猫中具有特定条件
问题描述
我有一个如下所示的数据框
UnitID Sector Start_Date Status
1 SE1 2018-02-26 Closed
1 SE1 2019-03-27 Active
2 SE1 2017-02-26 Closed
2 SE1 2018-02-26 Closed
2 SE1 2019-02-26 Active
3 SE1 NaT Not_in_contract
4 SE1 NaT Not_in_contract
5 SE2 2017-02-26 Closed
5 SE2 2018-02-26 Closed
5 SE2 2019-02-26 Active
6 SE2 2018-02-26 Closed
6 SE2 2019-02-26 Active
7 SE2 2018-02-26 Closed
7 SE2 2018-07-15 Closed
8 SE2 NaT Not_in_contract
9 SE2 NaT Not_in_contract
10 SE2 2019-05-22 Active
11 SE2 2019-06-24 Active
从上面我想准备下面的数据框
Sector Number_of_unique_units Number_of_Active_units
SE1 4 2
SE2 7 4
解决方案
使用GroupBy.agg
with和自定义 lambda 函数以及布尔掩码的计数DataFrameGroupBy.nunique
:Active
sum
df1=(df.groupby('Sector').agg(Number_of_unique_units=('UnitID','nunique'),
Number_of_Active_units=('Status',lambda x:x.eq('Active').sum()))
.reset_index())
print (df1)
Sector Number_of_unique_units Number_of_Active_units
0 SE1 4 2
1 SE2 7 4
推荐阅读
- c# - 在应用程序级别打开受密码保护的文档添加
- ios - 在文本中添加无限行(SwiftUI)
- java - 如何停止导致使用父类序列化程序的@JsonProperty?
- python - Python - 从提供的模式生成文件名
- python - 将 Session 与 HTTPAdapter 一起使用时,Python 请求不会引发异常
- php - foreach 循环仅输出数组中的最后一个元素
- javascript - 如何使用开始禁用但必须开始启用的组件?
- python - 某些 DAG 运行后气流回填中断的可能原因
- php - 在 Laravel 中检查用户的角色
- python - 从亚马逊抓取数据以创建产品跟踪代码