I have pandas DataFrame like this:
data = {'ID_1':['A', 'A','A', 'B', 'B', 'B'],
'ID_2':[1, 2, 2, 1, 1, 2],
'DATE':['2021-11-21', '2021-12-19', '2021-09-05', '2021-11-07', '2021-12-05','2021-12-26'],
'VALUE': [0.5, 0.5, 0.5, 0.6, 0.6, 0.6]}
df = pd.DataFrame(data)
And I would like to leave value in column 'VALUE' only for lowest date from column 'DATE' for subset of 'ID_1' and 'ID_2'
Desired output look like this:
data = {'ID_1':['A', 'A','A', 'B', 'B', 'B'],
'ID_2':[1, 2, 2, 1, 1, 2],
'DATE':['2021-11-21', '2021-12-19', '2021-09-05', '2021-11-07', '2021-12-05','2021-12-26'],
'VALUE': [0.5, np.NaN, 0.5, 0.6, np.NaN, 0.6]}
df = pd.DataFrame(data)
What I tried is to create function which twice grouping this dataframe but I'm ending with ValueError Length of values (2) does not match length of index (1)
My function:
def foo(val):
def add_mask(val):
val.reset_index(inplace=True)
min_date = val['DATE'].min()
mask = val.DATE == min_date
return val[mask]
return val.groupby('ID_1').apply(add_mask)
test = df.groupby('ID_2').apply(foo)