【问题标题】:How to take the semi last value per group如何取每组的最后一个值
【发布时间】:2019-12-11 17:06:14
【问题描述】:

我希望每个组都保留半倒数的值,如下所示。

ID number    
1   50    
1   49    
1   48
1   45    
2   47    
2   40    
2   31    
3   60    
3   51

示例输出

1  48

2  40

3  60

【问题讨论】:

  • df.groupby('ID')['number'].nth(-2) ..?

标签: pandas filter


【解决方案1】:

一个班轮:

df[df[::-1].groupby('ID').cumcount()[::-1]==1]

输出:

   ID  number
2   1      48
5   2      40
7   3      60

【讨论】:

    【解决方案2】:

    Groupby.nth-2 一起使用:

    df.groupby('ID')['number'].nth(-2)
    

    [出]

    ID
    1    48
    2    40
    3    60
    Name: number, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多