Pandas-基于数据帧的两个后续行查找差异

Pandas-基于数据帧的两个后续行查找差异,pandas,Pandas,我有一个数据框,用于捕获客户提交票据的日期,该日期在标有date的列中捕获。如果当前单元格的ref_列与下面的单元格相同,那么我需要根据date列查找当前单元格与下面相同cust_id的单元格的老化差异。如果ref_列是相同的,那么我需要找到同一行的date和ref_date之间的差异 下面给出了我的数据: cust_id,date,ref_column,ref_date 101,15/01/19,abc,31/01/19 101,17/01/19,abc,31/01/19 101,19/01/

我有一个数据框,用于捕获客户提交票据的日期,该日期在标有
date
的列中捕获。如果当前单元格的
ref_列
与下面的单元格相同,那么我需要根据
date
列查找当前单元格与下面相同
cust_id
的单元格的老化差异。如果ref_列是相同的,那么我需要找到同一行的
date
ref_date
之间的差异

下面给出了我的数据:

cust_id,date,ref_column,ref_date
101,15/01/19,abc,31/01/19
101,17/01/19,abc,31/01/19
101,19/01/19,xyz,31/01/19
102,15/01/19,abc,31/01/19
102,21/01/19,klm,31/01/19
102,25/01/19,xyz,31/01/19
103,15/01/19,xyz,31/01/19
预期产出:

cust_id,date,ref_column,ref_date,aging(in days)
101,15/01/19,abc,31/01/19,2
101,17/01/19,abc,31/01/19,14
101,19/01/19,xyz,31/01/19,0
102,15/01/19,abc,31/01/19,16
102,21/01/19,klm,31/01/19,10
102,25/01/19,xyz,31/01/19,0
103,15/01/19,xyz,31/01/19,0
账龄(以天为单位)
是给定
客户id的最后一个条目的0

以下是我的方法:

# convert dates to datetime type
# ignore if already are
df['date'] = pd.to_datetime(df['date'])
df['ref_date'] = pd.to_datetime(df['ref_date'])

# customer group
groups = df.groupby('cust_id')

# where ref_column is the same with the next:
same_ = df['ref_column'].eq(groups['ref_column'].shift(-1))

# update these ones
df['aging'] = np.where(same_, 
                       -groups['date'].diff(-1).dt.days,       # same ref as next row
                       df['ref_date'].sub(df['date']).dt.days) # diff ref than next row

# update last elements in groups:
last_idx = groups['date'].idxmax()
df.loc[last_idx, 'aging'] = 0
输出:

   cust_id       date ref_column   ref_date  aging
0      101 2019-01-15        abc 2019-01-31    2.0
1      101 2019-01-17        abc 2019-01-31   14.0
2      101 2019-01-19        xyz 2019-01-31    0.0
3      102 2019-01-15        abc 2019-01-31   16.0
4      102 2019-01-21        klm 2019-01-31   10.0
5      102 2019-01-25        xyz 2019-01-31    0.0
6      103 2019-01-15        xyz 2019-01-31    0.0

组中最后一个是否总是有
ref_列
xyz
?@QuangHoang不一定。这只是为了显示数据在数据框中的示例。它可以是任何价值。