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

marking same across rows if one of rows satisfy condition

How can I mark as ‘abuser’ across rows of same ID if one of rows of that ID satisfy a condition?

For example, if I have the following table,

ID social score
1 0
1 2
1 3
2 3
2 1
2 2

Can I mark rows of ID 1 as all abnormal (because social score of one of rows is 0 ) and mark rows of ID 2 as all normal (because social score of none of rows of ID 2 is 0 )?

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

ID social score class
1 0 ‘abnormal’
1 2 ‘abnormal’
1 3 ‘abnormal’
2 3 ‘normal’
2 1 ‘normal’
2 2 ‘normal’

If I can, with what python phrase?

>Solution :

You can use groupby then use transform and at the end, use map and dict to replace True, False with abnormal, normal:

import pandas as pd

df = pd.DataFrame({'ID':[1,1,1,2,2,2],'social score': [0,2,3,3,1,2]})

df['class'] = df.groupby(['ID'])['social score'].transform(
    lambda x : any(x.eq(0))).map({True:'abnornmal',False:'normal'})
print(df)

Output:

   ID  social score      class
0   1             0  abnornmal
1   1             2  abnornmal
2   1             3  abnornmal
3   2             3     normal
4   2             1     normal
5   2             2     normal
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