首页 > 解决方案 > 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

标签: pandaspandas-groupby

解决方案


使用GroupBy.aggwith和自定义 lambda 函数以及布尔掩码的计数DataFrameGroupBy.nuniqueActivesum

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

推荐阅读