Pandas - Groupby + Shift无法按预期工作

问题描述 投票:1回答:2

我有一个df,我正在尝试执行groupbyshift。但是,输出不是我想要的。

我想将“下一个”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)的路线,但它并没有让我到达我想要的地方。

python pandas group-by
2个回答
2
投票

定义函数f以根据移动日期执行替换 -

def f(x):
     i = x.drop_duplicates()
     j = i.shift(-1).fillna('10/30')

     return x.map(dict(zip(i, j)))

现在,在groupbyapply上的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

2
投票

达蒙

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)
© www.soinside.com 2019 - 2024. All rights reserved.