Pandas Groupby:两个子组都存在的选择



My DataFrame的格式如下:

id group color
i1 aa    white
i1 aa    white
i1 ab    white
i1 ab    black
...

我按如下方式应用groupby:

groupdf = df.groupby(['id', 'group'])['color'].value_counts()

groupby的结果有一个多索引

value
id group color 
i1  aa   white  2
i1  ab   white  1
i1  ab   black  3
i1  ac   black  5
i1  ad   white  4
i1  ad   black  5
i2  aa   white  1
i2  aa   black  1
i2  bb   black  1
i2  cc   white  2
i2  cc   black  6
i2  ad   black  5  

我的目标是

  1. 选择存在最后一个索引颜色的两个类别的条目,然后
  2. 选择黑色最大值的组所以结果看起来像:
value
id
i1  5    #only groups ab and ad have both colors; ad.black = 5 > ab.black = 3
i2  6    #only groups aa and cc have both colors; cc.black = 6 > aa.black = 1

我已经尝试过。xs()以及。index.get_level_values(),但我无法实现我的目标。

编辑1:我看到我提供了很差的信息,我是如何获得DataFrame并在上面更新它的。我不能直接插件。max(),因为原来的df没有值列。

我们试试:

# mask the groups with more than one colors
s = df.groupby(['id','group'])['value'].transform('size') > 1

# boolean index the groups and query, then another groupby with max
df[s].query('color=="black"').groupby(['id','color'])['value'].max()

输出:

id  color
i1  black    5
i2  black    6
Name: value, dtype: int64

最新更新