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

Groupby check last rows values, and return validation, pandas

I have the following df:

df = pd.DataFrame({'Id':[1,1,1,2,2,2,3,3,3],
                   'LastState':['JAY','JAY','JAY',np.nan,'penu hehe','penu hehe','JAY','penu hehe','POTATO IS A FRUIT']})

Is there a way i could check if the last two rows in the grouped series id, contains a specific string in this case ‘POTATO IS A FRUIT’, and then returning True or False on the group?

Wanted result

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

result = pd.DataFrame({'Id':[1,2,3],'LastState':[False,False,True]})

>Solution :

To check if any of the last 2 rows of each group contain 'POTATO IS A FRUIT':

df.groupby('Id').agg(lambda g: 
                        g.iloc[-2:].str.contains('POTATO IS A FRUIT').any()
                    ).reset_index()
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