【问题标题】:Pandas Groupby: selection where both subgroups existPandas Groupby:两个子组都存在的选择
【发布时间】:2021-12-01 05:17:45
【问题描述】:

我的 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 没有 value 列。

【问题讨论】:

    标签: python pandas group-by multi-index


    【解决方案1】:

    我们试试吧:

    # 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
    

    【讨论】:

    • 是的。创建临时 DF 后,您的代码就像魅力一样工作
    猜你喜欢
    • 2015-10-10
    • 1970-01-01
    • 2021-04-07
    • 2015-06-30
    • 1970-01-01
    • 2023-03-30
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多