Reputation: 467
This post is to assign value of last row to first row: Move last value to first value.
I would like to move the value in the second duplicate to the first duplicate and set others to NaT.
ID OutBedTime DateOutBed 1 16/05/2018 0:17 16/05/2018 1 16/05/2018 4:05 16/05/2018 1 16/05/2018 6:05 16/05/2018 1 17/05/2018 1:27 17/05/2018 1 17/05/2018 4:41 17/05/2018 1 17/05/2018 5:32 17/05/2018
Expected output
ID OutBedTime DateOutBed TimeOutBedFinal 1 16/05/2018 0:17 16/05/2018 16/05/2018 4:05 1 16/05/2018 4:05 16/05/2018 NaT 1 16/05/2018 6:05 16/05/2018 NaT 1 17/05/2018 1:27 17/05/2018 17/05/2018 4:41 1 17/05/2018 4:41 17/05/2018 NaT 1 17/05/2018 5:32 17/05/2018 NaT
Thank you.
Upvotes: 3
Views: 116
Reputation: 323326
Let us do reindex
with apply
and select the second of row , then do the same as we did from pervious question
df['New']=df.groupby('DateOutBed')['OutBedTime'].apply(lambda x : x.iloc[[1]]).reset_index(level=1,drop=True).reindex(df.DateOutBed).values
df['New']=df.New.mask(df.DateOutBed.duplicated())
df
ID OutBedTime DateOutBed New
0 1 16/05/20180:17 16/05/2018 16/05/20184:05
1 1 16/05/20184:05 16/05/2018 NaN
2 1 16/05/20186:05 16/05/2018 NaN
3 1 17/05/20181:27 17/05/2018 17/05/20184:41
4 1 17/05/20184:41 17/05/2018 NaN
5 1 17/05/20185:32 17/05/2018 NaN
Check the update
df['New']=df.groupby('DateOutBed')['OutBedTime'].transform(lambda x : x.iloc[1] if len(x)>1 else x.iloc[0])
df['New']=df.New.mask(df.DateOutBed.duplicated())
Upvotes: 2