Countif in Pandas Dataframe

Viewed 846

I'm trying to solve a really simple code. I have a dataframe where I want to use a Count If per row. The problem is that the result is that it counts all symbols per row, even if the condition is not met.

I'm probably missing someting.

This is the code I'm trying where I want to count how many number of 2 there are per row.

Twos = (df[cols] == 2).count(axis=1)

print(Twos)

I have 10 columns and it return 10 for all 1 million rows and this is not the correct outcome.

1 Answers

Since (df[cols] == 2) outputs a df of True or False values, and True is equivalent to 1, while False is equivalent to 0, you should use sum instead of count:

Twos = (df[cols] == 2).sum(axis=1)

count will count all non missing values, sum with a conditional filter will result in a count of values satisfying your condition.

Related