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
>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