【问题标题】:Python pandas: Compare rows of dataframe based on some columns and drop row with lowest valuePython pandas:根据某些列比较数据框的行并删除具有最低值的行
【发布时间】:2015-06-26 14:45:14
【问题描述】:

我有一个数据框 df:

       first_seen              last_seen             uri
0   2015-05-11 23:08:46     2015-05-11 23:08:50 http://11i-ssaintandder.com/
1   2015-05-11 23:08:46     2015-05-11 23:08:46 http://11i-ssaintandder.com/
2   2015-05-02 18:27:10     2015-06-06 03:52:03 http://goo.gl/NMqjd1
3   2015-05-02 18:27:10     2015-06-08 08:44:53 http://goo.gl/NMqjd1

我想删除具有相同“first_seen”、“uri”的行并仅保留具有最新 last_seen 的行。

这是expected 数据集的示例:

       first_seen              last_seen             uri
0   2015-05-11 23:08:46     2015-05-11 23:08:50 http://11i-ssaintandder.com/
3   2015-05-02 18:27:10     2015-06-08 08:44:53 http://goo.gl/NMqjd1

有谁知道不写 for 循环的情况下谁来做?

【问题讨论】:

    标签: python pandas compare dataframe rows


    【解决方案1】:

    调用drop_duplicates 并将您要考虑进行重复匹配的列作为subset 的参数传递并设置参数take_last=True

    In [295]:
    
    df.drop_duplicates(subset=['first_seen','uri'], take_last=True)
    Out[295]:
      index          first_seen            last_seen                           uri
    1     1 2015-05-11 23:08:46  2015-05-11 23:08:46  http://11i-ssaintandder.com/
    3     3 2015-05-02 18:27:10  2015-06-08 08:44:53          http://goo.gl/NMqjd1
    

    编辑

    为了获取最新日期,您需要先在 'first_seen' 和 'last_seen' 上对 df 进行排序:

    n [317]:
    df = df.sort(columns=['first_seen','last_seen'], ascending=[0,1])
    df.drop_duplicates(subset=['first_seen','uri'], take_last=True)
    
    Out[317]:
      index          first_seen            last_seen                           uri
    0     0 2015-05-11 23:08:46  2015-05-11 23:08:50  http://11i-ssaintandder.com/
    3     3 2015-05-02 18:27:10  2015-06-08 08:44:53          http://goo.gl/NMqjd1
    

    【讨论】:

    • @firelynx 好点会更新,但您不需要按 first_seen 和 last_seen 排序吗?
    • 我不明白你为什么会这样,但我不会太相信自己有这种头痛。
    • @firelynx 我认为它会更安全,因为与 first_seen 相比,last_seen 中的日期可能重叠,现在似乎满足了 OP 的要求
    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多