如何使用大 pandas 在匹配给定条件的列中求和值? [英] How do I sum values in a column that match a given condition using pandas?

查看:89
本文介绍了如何使用大 pandas 在匹配给定条件的列中求和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的列:

Suppose I have a column like so:

a   b  
1   5   
1   7
2   3
1   3
2   5

我想总结一下例如 b 其中 a = 1 的值。这将给我 5 + 7 + 3 = 15

I want to sum up the values for b where a = 1, for example. This would give me 5 + 7 + 3 = 15.

我如何在熊猫做这个? p>

How do I do this in pandas?

推荐答案

对于这种任务,使用布尔索引是很常见的。使用此方法,您可以找出列 a 等于 1 的位置,然后将列< c $ c> b 。您可以使用 loc 来处理索引:

It's quite common to use boolean indexing for this kind of task. With this method, you find out where column a is equal to 1 and then sum the corresponding rows of column b. You can use loc to handle the indexing:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

另一种方法是使用 groupby 根据 a 。然后,您可以对每个部分进行总结,并拉出1加起来的值:

The alternative approach is to use groupby to split the dataframe into parts according to the value in column a. You can then sum each part and pull out the value that the 1's added up to:

>>> df.groupby('a')['b'].sum()[1]
15

groupby 方法比使用布尔索引慢得多,但是如果要检查列中的其他值的总和 a

The groupby approach is much slower than using boolean indexing, but is useful if you want check the sums for other values in column a.

这篇关于如何使用大 pandas 在匹配给定条件的列中求和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆