pandas 计数和求和特定条件

2022-11-02Python开发问题
51

本文介绍了 pandas 计数和求和特定条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

pandas 中是否有单个函数可以执行 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) 或 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

如果你想做COUNTIF,只需将sum()替换成count()

If you want to do COUNTIF, just replace sum() with count()

这篇关于 pandas 计数和求和特定条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End
pandas

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10