熊猫-根据数据框的后两行查找差异

时间:2019-09-18 17:06:32

标签: pandas

我有一个数据框,该数据框捕获在date列中捕获的客户提出票证的日期。如果当前单元格的ref_column与以下单元格相同,那么我需要基于date列当前单元格和同一cust_id的后续单元格来查找老化差异。如果ref_column相同,那么我需要找到同一行的dateref_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
对于给定的Aging(in days)

cust_id的最后一个条目为0

1 个答案:

答案 0 :(得分:2)

这是我的方法:

# 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