代码之家  ›  专栏  ›  技术社区  ›  mlwh

基于每个唯一id的最新时间戳过滤数据帧[重复]

  •  4
  • mlwh  · 技术社区  · 7 年前

    标题可能有点混乱,下面是一个示例:

    发件人:

    id |     timestamp
     1 | 2015-12-02 00:00:00
     1 | 2015-12-03 00:00:00  <--- latest for id 1
     2 | 2015-12-02 00:00:00
     2 | 2015-12-04 00:00:00
     2 | 2015-12-06 00:00:00  <--- latest for id 2
    

    为此:

    id |     timestamp
     1 | 2015-12-03 00:00:00
     2 | 2015-12-06 00:00:00
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   Zero    7 年前

    使用 nth

    In [599]: df.groupby('id', as_index=False).nth(-1)
    Out[599]:
       id            timestamp
    1   1  2015-12-03 00:00:00
    4   2  2015-12-06 00:00:00
    

    理想的, max 因为你需要最晚的日期。

    In [601]: df.groupby('id', as_index=False).max()
    Out[601]:
       id            timestamp
    0   1  2015-12-03 00:00:00
    1   2  2015-12-06 00:00:00
    

    而且 tail 如评论中所述

    In [602]: df.groupby('id').tail(1)
    Out[602]:
       id            timestamp
    1   1  2015-12-03 00:00:00
    4   2  2015-12-06 00:00:00