如何在 pandas 中对分组后的数据进行正负值计数?

12

假设我们有一个表:

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
                   'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
                   'C' : np.random.randn(8), 'D' : np.random.randn(8)})

输出:

      A       B          C           D
0    foo     one    -1.304026    0.237045
1    bar     one     0.030488   -0.672931
2    foo     two     0.530976   -0.669559
3    bar     three  -0.004624   -1.604039
4    foo     two    -0.247809   -1.571291
5    bar     two    -0.570580    1.454514
6    foo     one     1.441081    0.096880
7    foo     three   0.296377    1.575791

我想要统计列C中每个A组中有多少正数和负数,并以何种比例。A列中的组很多,不仅限于"foo"和"bar",因此组名不能写在代码中。

我尝试对A进行分组,然后过滤,但没有找到正确的方法。还尝试了使用一些聪明的lambda函数进行聚合,但没有成功。

1个回答

14
你可以通过一行 apply 来实现这个目标(第一列为负数,第二列为正数):
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]

不过,我认为更简洁的方法是使用一个虚拟列并使用 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]

2
我认为我更喜欢 df["C_sign"] = np.sign(df.C) - DSM
@DSM同意,这样更好。 - Andy Hayden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接