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

python pandas "groupby" and "if any" condition

I have a dataframe similar to the one below, and I would like to create a new variable which contains true/false if for each project the sector "a" has been covered at least once.
I’m trying with the group.by() function, and wanted to use the .transform() method but since my data is text, I don’t know how to use it.

      project    sector  
    
        01         a    
        01         b    
        02         b     
        02         b     
        03         a     
        03         a     
    



 project    sector   new_col

    01         a     true
    01         b     true
    02         b     false
    02         b     false
    03         a     true
    03         a     true

       

>Solution :

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

You could try the following:

df['new_col'] = df.groupby('project')['sector'].transform(lambda x: (x == 'a').any() )

This will group by project and check if any ‘a’ is in the groups sectors

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