数据帧。
ID spend month_diff
12 10 -5
12 10 -4
12 10 -3
12 10 1
12 10 -2
12 20 0
12 30 2
12 10 -1
我想得到 spend_total
根据某个ID的月份差额计算。month_diff
负数表示客户在去年的消费,正数表示今年的消费。所以,我想比较一下客户去年和今年的花费,所以条件如下:条件。
if month_diff >= -2 and < 0
那么负数月的累计消费额-> flag=pre
if month_diff > 0 and <=2
则为正数月的累计消费->。flag=post
注:数量为 month_diff +ve
和 -ve
有可能是客户有4笔交易在 -ve month_diff
而只有2笔交易 +ve
所以我只想拿2个月的累计金额 -ve month_diff
和2个 +ve
而不想考虑花钱的地方。month_diff
是0。
希望的数据框架。
ID spend month_diff spend_tot flag
12 10 -2 20 pre
12 30 2 40 post
40是月差+1和+2的累计支出总和(即10+30),月差-1和-2也一样,其累计支出为20(即10+10)
使用。
#filter values by list
df = df[df['month_diff'].isin([1,2,-1,-2])]
#filter duplicated values with absolute values of month_diff
df = df[df.assign(a=df['month_diff'].abs()).duplicated(['ID','a'], keep=False)]
#sign column
a = np.sign(df['month_diff'])
#aggregate sum and last
df1 = (df.groupby(['ID', a])
.agg({'month_diff':'last', 'spend':'sum'})
.reset_index(level=1, drop=True)
.reset_index())
df1['flag'] = np.select([df1['month_diff'].ge(-2) & df1['month_diff'].lt(0),
df1['month_diff'].gt(0) & df1['month_diff'].le(2)],
['pre','post'], default='another val')
print (df1)
ID month_diff spend flag
0 12 -1 20 pre
1 12 2 40 post