How to drop duplicates in a data frame and keep first with two exceptions?

I have a data frame that looks like this.

import pandas as pd
  
# intialise data of lists.
data = {'ID':[101762, 101762, 102842, 102842, 106755, 106755, 108615, 108615, 113402, 113402, 114711, 114711],
        'Year':[2019, 2020, 2019, 2020, 2019, 2020, 2019, 2020, 2019, 2020, 2019, 2020],
        'Amount':[2091.06, 3330.00, 846.19, 846.19, 16185.60, 800, 281496.00, 1363730.00, 19815.00, 9585.00, 64332.70, 5400.00]}
  
# Create DataFrame
df = pd.DataFrame(data)
  
# Print the output.
df

Here is an image with some logic of what I am trying to do.

enter image description here

Need to drop anything where Amount = 0, or Year = 2012

df = df[df['Amount'] != 0]
df = df[df['Year'] != '2021']

Ok, so far. Now, I need to keep the max Amount if an ID & Year shows up more than once. Here is the code that I am running.

df = df.sort_values(['ID','Year']).drop_duplicates(['ID','Year'], keep='first')

At this point, things are still fine, but I’m stuck on the next steps. How can I do the following?

  1. If ID is repeated and 2020 Amount > 2019 Amount, sum these two Amounts together
  2. If ID is repeated and 2020 Amount = 2019 Amount, keep only 2020
  3. If ID is repeated and 2019 Amount > 2020 Amount, keep only 2019

How can I achieve these three objectives?

Answer

A little bit logic with sort_values

out = df.sort_values('Year',ascending=False).drop_duplicates(['ID','Amount']).sort_values('Amount').groupby('ID').agg({'Year':'last','Amount':'sum'}).reset_index()
       ID  Year      Amount
0  101762  2020     5421.06
1  102842  2020      846.19
2  106755  2019    16985.60
3  108615  2020  1645226.00
4  113402  2019    29400.00
5  114711  2019    69732.70