【问题标题】:Pandas GroupBy - Show only groups with more than one unique feature-valuePandas GroupBy - 仅显示具有多个唯一特征值的组
【发布时间】:2018-12-30 16:05:51
【问题描述】:

我有一个看起来像这样的 DataFrame df_things,我想在训练之前预测分类的质量

A    B     C      CLASS
-----------------------
al1  bal1  cal1   Ship
al1  bal1  cal1   Ship
al1  bal2  cal2   Ship
al2  bal2  cal2   Cow
al3  bal3  cal3   Car
al1  bal2  cal3   Car
al3  bal3  cal3   Car

我想按类对行进行分组,以便了解特征的分布。我这样做(例如,在 col "B" 上),

df_B = df_things.groupby('CLASS').B.value_counts()

这给了我结果

CLASS  B 
-------------
ship   bal1  2 
       bal2  1
cow    bal2  2
car    bal2  1
       bal3  2

我想要的是仅可视化具有多个值的组,使其看起来像这样:

CLASS  B 
-------------
ship   bal1  2 
       bal2  1
car    bal2  1
       bal3  2

我有点卡住了,有什么想法吗?

【问题讨论】:

    标签: python pandas compare unique pandas-groupby


    【解决方案1】:

    您可以使用groupby 过滤nunique 计数大于1 的组。

    v = df_things.groupby('CLASS').B.value_counts()
    v[v.groupby(level=0).transform('nunique').gt(1)]
    
    CLASS  B   
    Car    bal3    2
           bal2    1
    Ship   bal1    2
           bal2    1
    Name: B, dtype: int64
    

    【讨论】:

    • 非常感谢 - 正是我想要的!
    • 感谢您编辑我的帖子。它可以帮助我以更准确的方式提出问题!
    • @FelTry2 只是做网站的好公民。继续提问!
    【解决方案2】:

    来自crosstab的解决方案

    s=pd.crosstab(df.CLASS,df.B)
    s[s.ne(0).sum(1)>1].replace(0,np.nan).stack()
    CLASS  B   
    Car    bal2    1.0
           bal3    2.0
    Ship   bal1    2.0
           bal2    1.0
    dtype: float64
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 2021-10-25
      • 2011-12-30
      • 2020-09-08
      • 2016-08-12
      相关资源
      最近更新 更多