Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to do countif in Python

Tags:

python

I want to count how many members of an iterable meet a given condition. I'd like to do it in a way that is clear and simple and preferably reasonably optimal.

My current best ideas are:

sum(meets_condition(x) for x in my_list) 

and

len([x for x in my_list if meets_condition(x)]) 

The first one being iterator based is presumably faster for big lists. And it's the same form as you'd use for testing any and all. However it depends on the fact that int(True) == 1, which is somewhat ugly.

The second one seems easier to read to me, but it is different from the any and all forms.

Does anyone have any better suggestions? is there a library function somewhere that I am missing?

like image 590
Gordon Wrigley Avatar asked Apr 15 '10 08:04

Gordon Wrigley


People also ask

How do I use COUNTIFs in pandas?

COUNTIF, COUNTIFs And Many Others In Pandas Since you have already mastered SUMIF and SUMIFS in pandas, to do COUNTIF(S), all we need is to replace the sum() operation with the count() operation. In fact, if we replace sum() in the above examples with: mean() – will give AVERAGEIF(S) max() – will give MAXIFS.

Is there a count method in Python?

Count() is a Python built-in function that returns the number of times an object appears in a list. The count() method is one of Python's built-in functions. It returns the number of times a given value occurs in a string or a list, as the name implies.


2 Answers

The iterator based approach is just fine. There are some slight modifications that can emphasize the fact that you are counting:

sum(1 if meets_condition(x) else 0 for x in my_list) # or  sum(1 for x in my_list if meets_condition(x)) 

And as always, if the intent isn't apparent from the code, encapsulate it in descriptively named function:

def count_matching(condition, seq):     """Returns the amount of items in seq that return true from condition"""     return sum(1 for item in seq if condition(item))  count_matching(meets_condition, my_list) 
like image 73
Ants Aasma Avatar answered Sep 25 '22 22:09

Ants Aasma


The first one

sum(meets_condition(x) for x in my_list) 

looks perfectly readable and pythonic to me.

If you prefer the second approach I'd go for

len(filter(meets_condition, my_list)) 

Yet another way could be:

map(meets_condition, my_list).count(True) 
like image 40
ChristopheD Avatar answered Sep 25 '22 22:09

ChristopheD