我的数据如下:
Customer Product Date Amount Paid
C1 P1 5/10/2011 100
C1 P1 5/18/2015 200
C1 P1 6/17/2019 300
C2 P2 4/18/2019 50
我想为每个客户和产品,最后两个金额之间的差异支付的日期,第一次和最后一次支付的金额之间的差异。以及支付的最高金额和最低金额之间的差异。
对于只有一笔交易的客户,这些值变为0。因此,输出应如下所示:
Customer Product Diff_first_last Diff_last_two Diff_min_max
C1 P1 200 100 200
C2 P2 0 0 0
发布于 2019-10-29 03:21:04
下面是传递到apply
的一种方法
df.groupby(['Customer','Product']).Amount.apply(lambda x : pd.Series({'Diff_first_last':x.iloc[0]-x.iloc[-1],
'Diff_last_two':x.iloc[-2:].diff().fillna(0).iloc[-1],
'Diff_min_max':np.ptp(x)})).unstack()
Diff_first_last Diff_last_two Diff_min_max
Customer Product
C1 P1 -200.0 100.0 200.0
C2 P2 0.0 0.0 0.0
https://stackoverflow.com/questions/58600991
复制