本文介绍了将第二个副本中的值移动到第一个副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这篇文章是将最后一行的值赋值给第一行:Move last value to第一个值.
我想将第二个副本中的值移动到第一个副本,并将其他副本设置为 NaT.
ID OutBedTime DateOutBed1 16/05/2018 0:17 16/05/20181 16/05/2018 4:05 16/05/20181 16/05/2018 6:05 16/05/20181 17/05/2018 1:27 17/05/20181 17/05/2018 4:41 17/05/20181 17/05/2018 5:32 17/05/2018预期输出
ID OutBedTime DateOutBed TimeOutBedFinal1 16/05/2018 0:17 16/05/2018 16/05/2018 4:051 16/05/2018 4:05 16/05/2018 NaT1 16/05/2018 6:05 16/05/2018 NaT1 17/05/2018 1:27 17/05/2018 17/05/2018 4:411 17/05/2018 4:41 17/05/2018 NaT1 17/05/2018 5:32 17/05/2018 NaT谢谢.
解决方案
让我们用 apply
做 reindex
并选择第二行,然后和我们一样来自上一个问题
df['New']=df.groupby('DateOutBed')['OutBedTime'].apply(lambda x : x.iloc[[1]]).reset_index(level=1,drop=真).reindex(df.DateOutBed).valuesdf['New']=df.New.mask(df.DateOutBed.duplicated())dfID OutBedTime DateOutBed 新0 1 16/05/20180:17 16/05/2018 16/05/20184:051 1 16/05/20184:05 16/05/2018 NaN2 1 16/05/20186:05 16/05/2018 NaN3 1 17/05/20181:27 17/05/2018 17/05/20184:414 1 17/05/20184:41 17/05/2018 NaN5 1 17/05/20185:32 17/05/2018 NaN
检查更新
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())
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.
解决方案
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())
这篇关于将第二个副本中的值移动到第一个副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!