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

Get groups where values go from 0 to 1

I want to get all the users from a dataframe where a specific column goes from 1 to 0.

For example, with the following dataframe I want to keep only user 1 and 2 as their values go from 1 to 0.

Relevant rows

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

  • Row 6 to 7 for user 1
  • Row 9 to 10 for user 2
    user  value
0      0      0
1      0      0
2      0      1
3      0      1
4      1      0
5      1      1
6      1      1
7      1      0
8      2      1
9      2      1
10     2      0
11     2      0

Desired Result

    user  value
4      1      0
5      1      1
6      1      1
7      1      0
8      2      1
9      2      1
10     2      0
11     2      0

I have tried window functions and conditions but for some reason I cannot get the desired result.

>Solution :

Let us try cummax

df.loc[df.user.isin(df.loc[df.value != df.groupby('user')['value'].cummax(),'user'])]
Out[769]: 
    user  value
4      1      0
5      1      1
6      1      1
7      1      0
8      2      1
9      2      1
10     2      0
11     2      0
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