gpt4 book ai didi

python - 如何计算 pandas groupby 中的所有正值和负值?

转载 作者:太空狗 更新时间:2023-10-29 21:37:25 25 4
gpt4 key购买 nike

假设我们有一张表:

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 进行聚合,但没有成功。

最佳答案

您可以将此作为一行应用(第一列为负数,第二列为正数):

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]

关于python - 如何计算 pandas groupby 中的所有正值和负值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21296945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com