[英]How to count all positive and negative values in a pandas groupby?
Let's assume we have a table: 我们假设我们有一张桌子:
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)})
Output: 输出:
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
I want to count how many positive and negative numbers in column C belong to each group in column A and in what proportion. 我想计算C列中有多少正负数属于A列中的每个组以及具有多大比例。 There are much more groups in A than foo and bar, so group names shouldn't be in the code.
A中的组比foo和bar多得多,因此组名不应该在代码中。
I was trying to groupby A and then filter, but didn't find the right way. 我试图用A组合然后过滤,但没找到正确的方法。 Also tried to aggregate with some smart lambda, but didn't succeed.
还试图与一些聪明的lambda聚合,但没有成功。
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
: 但是,我认为更简洁的方法是使用虚拟列并使用
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.