rayqz
rayqz

Reputation: 259

Count rows that have same value in all columns

If I have a dataframe like this:

A  B  C  D  E  F      
------------------
1  2  3  4  5  6
1  1  1  1  1  1
0  0  0  0  0  0
1  1  1  1  1  1

How can I get the number of rows that have value 1 in every column? In this case, 2 rows have 1 in every field.

I know one way, for example if we only take columns A and B:

count = df2.query("A == 1 & B == 1").shape[0]

But I have to put the name of every column, is there a more fancy approach?

Thanks in advance

Upvotes: 4

Views: 466

Answers (2)

BENY
BENY

Reputation: 323236

For the large data frame and multiple row , you may always want to try with any , since when it detect the first item , it will yield the result

sum(~df.ne(1).any(1))
2

Upvotes: 3

Scott Boston
Scott Boston

Reputation: 153460

Try:

(df == 1).all(axis=1).sum()

Output:

2

Upvotes: 4

Related Questions