假设我们有一个表:
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函数进行聚合,但没有成功。
df["C_sign"] = np.sign(df.C)
。 - DSM