我有一个df,我正在尝试执行groupby
和shift
。但是,输出不是我想要的。
我想将“下一个”DueDate
转移到以前的日期。因此,如果当前的DueDate
是1/1,并且下一个DueDate
是6/30,那么在NextDueDate
的所有行中插入一个新的列,其中DueDate==1/1
是6/30。然后,当前的DueDate
是6/30,然后为DueDate
的所有行插入下一个DueDate==6/30
。
Original df
ID Document Date DueDate
1 ABC 1/31 1/1
1 ABC 2/28 1/1
1 ABC 3/31 1/1
1 ABC 4/30 6/30
1 ABC 5/31 6/30
1 ABC 6/30 7/31
1 ABC 7/31 7/31
1 ABC 8/31 9/30
Desired output df
ID Document Date DueDate NextDueDate
1 ABC 1/31 1/1 6/30
1 ABC 2/28 1/1 6/30
1 ABC 3/31 1/1 6/30
1 ABC 4/30 6/30 7/31
1 ABC 5/31 6/30 7/31
1 ABC 6/30 7/31 9/30
1 ABC 7/31 7/31 9/30
1 ABC 8/31 9/30 10/31
我有许多变化沿着df['NextDueDate'] = df.groupby(['ID','Document'])['DueDate'].shift(-1)
的路线,但它并没有让我到达我想要的地方。
定义函数f
以根据移动日期执行替换 -
def f(x):
i = x.drop_duplicates()
j = i.shift(-1).fillna('10/30')
return x.map(dict(zip(i, j)))
现在,在groupby
和apply
上的ID
+ Document
中调用此函数 -
df['NextDueDate'] = df.groupby(['ID', 'Document']).DueDate.apply(f)
df
ID Document Date DueDate NextDueDate
0 1 ABC 1/31 1/1 6/30
1 1 ABC 2/28 1/1 6/30
2 1 ABC 3/31 1/1 6/30
3 1 ABC 4/30 6/30 7/31
4 1 ABC 5/31 6/30 7/31
5 1 ABC 6/30 7/31 9/30
6 1 ABC 7/31 7/31 9/30
7 1 ABC 8/31 9/30 10/30
达蒙
s=df.groupby('DueDate',as_index=False).size().to_frame('number').reset_index()
s.DueDate=s.DueDate.shift(-1).fillna('10/31')
s
Out[251]:
DueDate number
0 6/30 3
1 7/31 2
2 9/30 2
3 10/31 1
s.DueDate.repeat(s.number)
Out[252]:
0 6/30
0 6/30
0 6/30
1 7/31
1 7/31
2 9/30
2 9/30
3 10/31
Name: DueDate, dtype: object
df['Nextduedate']=s.DueDate.repeat(s.number).values
df
Out[254]:
ID Document Date DueDate Nextduedate
0 1 ABC 1/31 1/1 6/30
1 1 ABC 2/28 1/1 6/30
2 1 ABC 3/31 1/1 6/30
3 1 ABC 4/30 6/30 7/31
4 1 ABC 5/31 6/30 7/31
5 1 ABC 6/30 7/31 9/30
6 1 ABC 7/31 7/31 9/30
7 1 ABC 8/31 9/30 10/31
如果您有多个组:
l=[]
for _, df1 in df.groupby(["ID", "Document"]):
s = df1.groupby('DueDate', as_index=False).size().to_frame('number').reset_index()
s.DueDate = s.DueDate.shift(-1).fillna('10/31')
df1['Nextduedate'] = s.DueDate.repeat(s.number).values
l.append(df1)
New_df=pd.concat(l)