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

Add Column with a count of other columns that have any value in

My data frame is similar to below:

Name   Col1 Col2 Col3 Col4 Col5 Col6    
A      Y    Y         Y             
B      Y         Y    Y         Y
C           Y    Y          Y       
D      Y    

I want to add a column that counts the other columns containing a value similar to:

Name   Col1 Col2 Col3 Col4 Col5 Col6  Score
A      Y    Y         Y               3
B      Y         Y    Y         Y     4
C           Y    Y          Y         3
D      Y                              1

I have tried the following but with no success:

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

df['Score'] = df.count(df[['Col1','Col2','Col3','Col4','Col5','Col6']], axis='columns')

>Solution :

If there are missing values use DataFrame.count with subset of columns:

df['Score'] = df[['Col1','Col2','Col3','Col4','Col5','Col6']].count(axis=1)
print (df)
  Name Col1 Col2 Col3 Col4 Col5 Col6  Score
0    A    Y    Y  NaN    Y  NaN  NaN      3
1    B    Y  NaN    Y    Y  NaN    Y      4
2    C  NaN    Y    Y  NaN    Y  NaN      3
3    D    Y  NaN  NaN  NaN  NaN  NaN      1
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