I am trying to handle the following dataframe.
import pandas as pd
import numpy as np
df = pd.DataFrame({'ID':[1,1,2,2,2,3,3,3,3],
'sum':[1,1,1,2,3,1,4,4,4],
'flg':[1,np.nan, 1, np.nan, np.nan, 1, 1, np.nan, np.nan],
'year':[2018, 2019, 2018, 2019, 2020, 2018, 2019, 2020, 2021]})
df['diff'] = df.groupby('ID')['sum'].apply(lambda x: x - x.iloc[-1])
The 'diff' is the difference from the 'sum' of the final year of each ID.
So, I tried the following code to remove the final year row used for comparison.
comp = df.groupby('ID').last().reset_index()
col = list(df.columns)
fin =pd.merge(df, comp, on=col, how='outer', indicator=True).query(f'_merge != "both"')
But here is where the problem arises.
The contents of 'comp' are as follows.
The 'comp' I originally wanted to get is below.
ID sum flg year diff
1 1 Nan 2019 0
2 3 Nan 2020 0
3 4 Nan 2021 0
Why is the Nan in 'flg' being complemented to 1 by itself? Please let me know if there is a better way to do this.

