Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 315
rayqz Avatar asked Mar 01 '23 10:03

rayqz


2 Answers

Try:

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

Output:

2
like image 108
Scott Boston Avatar answered Mar 11 '23 17:03

Scott Boston


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
like image 31
BENY Avatar answered Mar 11 '23 17:03

BENY