pandas groupby count the number of zeros in a column

后端 未结 3 2077
时光说笑
时光说笑 2021-02-04 20:49

I have a dataframe, e.g:

Date             B           C   
20.07.2018      10           8
20.07.2018       1           0
21.07.2018       0           1
21.07.201         


        
相关标签:
3条回答
  • 2021-02-04 20:58

    I believe need DataFrameGroupBy.agg with compare by 0 and sum:

    df1 = df.groupby('Date').agg(lambda x: x.eq(0).sum())
    print (df1)
    
                B  C
    Date            
    20.07.2018  0  1
    21.07.2018  1  1
    

    df2 = df.groupby('Date').agg(lambda x: x.ne(0).sum())
    print (df2)
                B  C
    Date            
    20.07.2018  2  1
    21.07.2018  1  1
    
    0 讨论(0)
  • 2021-02-04 21:04

    Try also:

    df.groupby('Date').agg(lambda x: len(x) - x.astype(bool).sum(axis=0))
    

    Output:

    Out[48]: 
                B  C
    Date            
    20.07.2018  0  1
    21.07.2018  1  1
    
    0 讨论(0)
  • 2021-02-04 21:17

    Using melt, then groupby

    Newdf=df.melt('Date')
    Newdf.value=Newdf.value.eq(0).astype(int)
    
    Newdf.groupby(['Date','variable']).value.value_counts().unstack([1,2]).sort_index(level=0,axis=1)
    Out[69]: 
    variable      B         C     
    value         0    1    0    1
    Date                          
    20.07.2018  NaN  2.0  1.0  1.0
    21.07.2018  1.0  1.0  1.0  1.0
    
    0 讨论(0)
提交回复
热议问题