Python 熊猫-Groupby+;班次未按预期工作
我有一个df,我正在尝试执行Python 熊猫-Groupby+;班次未按预期工作,python,pandas,group-by,pandas-groupby,Python,Pandas,Group By,Pandas Groupby,我有一个df,我正在尝试执行groupby和shift打开。然而,输出不是我想要的 我想将“下一个”DueDate切换到以前的日期。因此,如果当前的DueDate是1/1,下一个DueDate是6/30,那么对于DueDate==1/1的所有行,插入一个新列,其中NextDueDate是6/30。然后,当当前DueDate为6/30时,为DueDate==6/30的所有行插入下一个DueDate Original df ID Document Date DueDate 1 ABC
groupby
和shift
打开。然而,输出不是我想要的
我想将“下一个”DueDate
切换到以前的日期。因此,如果当前的DueDate
是1/1,下一个DueDate
是6/30,那么对于DueDate==1/1
的所有行,插入一个新列,其中NextDueDate
是6/30。然后,当当前DueDate
为6/30时,为DueDate==6/30的所有行插入下一个DueDate
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)
方面有很多变化,但这并不能完全满足我的需要。
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)
定义一个函数f
以根据已转移的日期执行替换-
def f(x):
i = x.drop_duplicates()
j = i.shift(-1).fillna('10/30')
return x.map(dict(zip(i, j)))
现在,在ID
和文档上的groupby
+apply
中调用此函数
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
如果他在一个有多个ID
和Document
类别的数据框架上操作,你不需要groupby([“ID”,“Document”,“DueDate”])
才能得到一个可概括的结果吗?我就是这么想的。代码一直工作到最后一部分。我得到一个值错误,即值的长度与索引的长度不匹配。@WaltReed您填写了吗?@WaltReed然后您需要查看您的样本数据,它是否可以重现您的问题,根据您的样本数据,我无法重现问题…sry