Skip to content Skip to sidebar Skip to footer

Move The Value In The Second Duplicate To The First Duplicate

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

Solution 1:

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

Post a Comment for "Move The Value In The Second Duplicate To The First Duplicate"