【问题标题】:Subtracting values of a row for a specific column based on a specific condition in python dataframe根据python数据框中的特定条件减去特定列的行值
【发布时间】:2020-02-24 07:31:02
【问题描述】:

我的数据如下所示:

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

【问题讨论】:

  • 创建一个字典,其中键是(客户、产品)元组,值包含有关第一个日期和金额、最后一个日期和金额、倒数第二个日期和金额以及最小值和最大值的信息成立。对整个数据完成此操作后,它就像遍历 dict 并计算值一样简单。

标签: python python-3.x pandas pandas-groupby


【解决方案1】:

这是传递给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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多