Home > OS >  Count rows that have same value in all columns
Count rows that have same value in all columns

Time:10-03

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

CodePudding user response:

Try:

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

Output:

2

CodePudding user response:

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
  • Related