Vineeth Sai
Vineeth Sai

Reputation: 27

How to count the number of rows that have the value 1 for all the columns in a dataframe?

The following is an example dataframe for this issue:

name    gender    address    phone no.
---------------------------------------
1       1         1          1
1       0         0          0
1       1         1          1
1       1         0          1

The desired output here is 2 because the number of rows containing all 1s is 2.

Can anyone please help me with this issue? Thanks.

Upvotes: 1

Views: 637

Answers (3)

Azhar Khan
Azhar Khan

Reputation: 4098

Assuming above dataframe is a binary table i.e. all values are either 1 or 0, then df.sum(axis=1) equal to 4 should give you all rows where all values are 1.

df[df.sum(axis=1) == len(df.columns)]

   name  gender  address  phone no.
0     1       1        1          1
2     1       1        1          1

Upvotes: 1

Ynjxsjmh
Ynjxsjmh

Reputation: 30022

Let's do

l = sum(df.eq(1).all(axis=1))
print(l)

2

Upvotes: 1

mozway
mozway

Reputation: 260530

Use eq(1) to identify the values with 1, then aggregate per row with any to have True when all values are True and sum the True taking advantage of the True/1 equivalence:

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

output: 2

Intermediates:

df.eq(1)
   name  gender  address  phone no.
0  True    True     True       True
1  True   False    False      False
2  True    True     True       True
3  True    True    False       True

df.eq(1).all(axis=1)
0     True
1    False
2     True
3    False
dtype: bool

Upvotes: 2

Related Questions