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

Calculate value difference using min and max dates

I am trying to calculate value growth/decline using the minimum date and maximum date. My data currently looks like this:

    Code      Date        Value
0   A         2020-12-31  80122.0
1   A         2019-12-31  45472.0
2   A         2018-12-31  31917.0
3   A         2017-12-31  23432.0
4   B         2020-12-31      0.0

For Code A I need to keep the max (2020-12-31) and min (2017-12-31) dates as well as the values so I can calculate the difference later on. I have multiple codes and need to be able to apply the same logic to each one. Any suggestions on the best way to approach this?

Thanks

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 :

In your case, you want to sort the date, then groupby and extract first, last:

 df.sort_values(['Code','Date']).groupby('Code')['Value'].agg(['first','last'])

Output:

        first     last
Code                  
A     23432.0  80122.0
B         0.0      0.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