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

Selecting the first two rows based on condition

I have a database like this :

ID Value
12345 123.78
12345 556.87
12345 1638.09
12345 133.44
56789 44
56789 434.2
56789 24.44

And i want my output to select the first two rows of each ID found and place the earliest value as new value and the oldest one as old value :

ID New Value Old Value
12345 123.78 556.87
56789 44 434.2

Thanks a lot for your help!

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

>Solution :

This is a variation on a pivot with filtering of the data:

out = (df
   .assign(col=lambda d: d.groupby('ID').cumcount())  # enumerate values
   .query('col < 2') # select top 2 per group
   .pivot(index='ID', columns='col', values='Value')  # reshape
   .set_axis(['New Value', 'Old Value'], axis=1).reset_index() # clean-up
)

Output:

      ID  New Value  Old Value
0  12345     123.78     556.87
1  56789      44.00     434.20
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