How to count all positive and negative values in a pandas groupby?

后端 未结 1 1927
故里飘歌
故里飘歌 2021-02-14 18:15

Let\'s assume we have a table:

df = pd.DataFrame({\'A\' : [\'foo\', \'bar\', \'foo\', \'bar\', \'foo\', \'bar\', \'foo\', \'foo\'],
                   \'B\' : [\         


        
1条回答
  •  不知归路
    2021-02-14 19:00

    You could do this as a one line apply (the first column being negative, the second positive):

    In [11]: df.groupby('A').C.apply(lambda x: pd.Series([(x < 0).sum(), (x >= 0).sum()])).unstack()
    Out[111]: 
         0  1
    A        
    bar  2  1
    foo  2  3
    
    [2 rows x 2 columns]
    

    However, I think a neater way is to use a dummy column and use value_counts:

    In [21]: df['C_sign'] = np.sign(df.C)
    
    In [22]: df.groupby('A').C_sign.value_counts()
    Out[22]: 
    A      
    bar  -1    2
          1    1
    foo   1    3
         -1    2
    dtype: int64
    
    In [23]: df.groupby('A').C_sign.value_counts().unstack()
    Out[23]: 
         -1   1
    A          
    bar   2   1
    foo   2   3
    
    [2 rows x 2 columns]
    

    0 讨论(0)
提交回复
热议问题