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
Try:
(df == 1).all(axis=1).sum()
Output:
2
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With