【问题标题】:Python/Pandas: How to Get the Last 3 of Each Group and Put into a List of ListsPython/Pandas:如何获取每个组的最后 3 个并放入列表列表
【发布时间】:2017-07-05 04:13:20
【问题描述】:

我想按“自动编号”对这个 DataFrame 进行分组并获取每个的最后 2 个数量,然后放入列表列表中

                        LoanAgreementID   Amount TransactionDate  \
0  252357C2-24C2-E611-8126-06CAB7997043  1667.35      2016-12-14   
1  252357C2-24C2-E611-8126-06CAB7997043  4181.28      2016-12-14   
2  4BF6F3D3-30C2-E611-8126-06CAB7997043  1667.35      2016-12-14   
3  4BF6F3D3-30C2-E611-8126-06CAB7997043  4181.28      2016-12-14   
4  4BF6F3D3-30C2-E611-8126-06CAB7997043   147.51      2017-01-18   
5  4BF6F3D3-30C2-E611-8126-06CAB7997043   147.51      2017-02-01   

                              ContactID  PaymentType  CashLedgerType  \
0  000FF848-42BE-E611-8126-06CAB7997043          NaN               5   
1  000FF848-42BE-E611-8126-06CAB7997043          NaN               5   
2  000FF848-42BE-E611-8126-06CAB7997043          NaN               5   
3  000FF848-42BE-E611-8126-06CAB7997043          NaN               5   
4  000FF848-42BE-E611-8126-06CAB7997043          0.0               3   
5  000FF848-42BE-E611-8126-06CAB7997043          0.0               3   

  KeyValue_String KeyValue_String.1  AutoNumber  IssueDate date_helper  
0          Cheque               NaN       54940 2016-12-14  2016-12-14  
1          Cheque               NaN       54940 2016-12-14  2016-12-14  
2          Cheque               NaN       54945 2016-12-14  2016-12-14  
3          Cheque               NaN       54945 2016-12-14  2016-12-14  
4         Payment               PAP       54945 2016-12-14  2017-01-18  
5         Payment               PAP       54945 2016-12-14  2017-02-01  
0    1667.35
1    4181.28
3    4181.28
4     147.51
5     147.51
Name: Amount, dtype: float64

使用下面的代码...

Amount_ref = group.groupby('AutoNumber')['Amount'].tail(2)

我得到了输出...

0    1667.35
1    4181.28
4     147.51
5     147.51
Name: Amount, dtype: float64

但我想要的输出是......

[[1667.35, 4181.28], [147.51, 147.51]]

【问题讨论】:

    标签: python pandas indexing dataframe group-by


    【解决方案1】:

    您可以使用applytolist

    Amount_ref = group.groupby('AutoNumber')['Amount']
                      .apply(lambda x: x.tail(2).tolist()).tolist()
    print (Amount_ref)
    [[1667.35, 4181.28], [147.51, 147.51]]
    

    或者:

    Amount_ref = group.groupby('AutoNumber')['Amount']
                      .apply(lambda x: x.iloc[-2:].tolist()).tolist()
    print (Amount_ref)
    [[1667.35, 4181.28], [147.51, 147.51]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多