Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to count number of times a condition is met across a row?

I have the following DataFrame

df = pd.DataFrame({'name': ['steve', 'josh', 'mike'],
                   'one': [0.4, 0.8, 0.2],
                   'two': [1, 0.1, 0.1],
                   'three': [1, 1, 0.99]})

that looks like this

name   one   two  three  
steve  0.4   1    1
josh   0.8   0.1  1
mike   0.2   0.1  0.99

I would like to add a new column to this table that counts how many times a specific condition is met across each row. If a value is not equal to 1, then count it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The result should look like this

name   one   two  three  sums
steve  0.4   1    1      1
josh   0.8   0.1  1      2
mike   0.2   0.1  0.99   3

I’m really unsure how to approach this.

>Solution :

My translation of "If a value is not equal to 1, then count it" (using select_dtypes to consider only numeric columns):

df['sums'] = df.select_dtypes('number').ne(1).sum(axis=1)

print(df)

    name  one  two  three  sums
0  steve  0.4  1.0   1.00     1
1   josh  0.8  0.1   1.00     2
2   mike  0.2  0.1   0.99     3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading