Python Pandas计数和求和特定条件 [英] Python Pandas counting and summing specific conditions
问题描述
熊猫中是否有单个函数可以执行 SUMIF ,它对特定条件和 COUNTIF ,它可以从Excel中计算特定条件的值?
Are there single functions in pandas to perform the equivalents of SUMIF, which sums over a specific condition and COUNTIF, which counts values of specific conditions from Excel?
我知道可以使用许多多步功能
I know that there are many multiple step functions that can be used for
例如sumif
,我可以先使用(df.map(lambda x: condition), or df.size())
,然后再使用.sum()
for example for sumif
I can use (df.map(lambda x: condition), or df.size())
then use .sum()
,对于countif
,我可以使用(groupby functions
并寻找答案,或者使用过滤器和.count())
and for countif
I can use (groupby functions
and look for my answer or use a filter and the .count())
在输入条件和数据框并获得总和或计数结果时,是否有简单的一步过程即可完成这些功能?
Is there simple one step process to do these functions where you enter the condition and the data frame and you get the sum or counted results?
推荐答案
您可以先进行条件选择,然后使用sum
函数汇总选择的结果.
You can first make a conditional selection, and sum up the results of the selection using the sum
function.
>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()
a 5
dtype: int64
具有多个条件:
>> df[(df.a > 1) & (df.a < 3)].sum()
a 2
dtype: int64
这篇关于Python Pandas计数和求和特定条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!