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.
CodePudding user response:
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
CodePudding user response:
Let's do
l = sum(df.eq(1).all(axis=1))
print(l)
2
CodePudding user response:
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