【问题标题】:Python 3 getting unique result base in date/time when multiple entry in the same date but different times当多个条目在同一日期但不同时间时,Python 3 在日期/时间中获得唯一的结果库
【发布时间】:2018-10-27 20:21:11
【问题描述】:

我是 python 新手,我一直在寻找解决这个问题的方法 我确定解决方案很简单,但我还没想好。 如果将其从打印输出中输出,可以说:

for x in data:
    print('x')

('Rodriguez, Cesar', '000500', '2018-05-15 8:09:12')
('Rodriguez, Cesar', '000500', '2018-05-15 12:09:12')
('Rodriguez, Cesar', '000500', '2018-05-15 12:09:12')
('Gura, Simon', '000501', '2018-05-15 09:09:12')

我如何才能为每个名称和每个代码以及最新日期获得一个结果。 所以我的结果应该是这样的:

('Rodriguez, Cesar', '000500', '2018-05-15 12:09:12')
('Gura, Simon', '000501', '2018-05-15 09:09:12')

但我不在乎答案是否是元组。它可以是一个列表或任何东西。 我唯一需要的是按名称、idcode 和最新条目进行过滤。 谢谢大家的帮助 最好的。

【问题讨论】:

    标签: python python-3.x pandas numpy datetime


    【解决方案1】:

    你可以像这样使用字典和循环:

    latest = {}
    for name, code, timestamp in data:
        key = (name, code)
        if key not in latest or latest[key] > timestamp:
            latest[key] = timestamp
    

    latest 中的结果将是:

    {('Gura, Simon', '000501'): '2018-05-15 09:09:12',
     ('Rodriguez, Cesar', '000500'): '2018-05-15 12:09:12'}
    

    注意:这使用字符串比较来比较时间戳。如果您的数据确实有时间格式化,而不像 '8:09:12' 中的前导零,那么您需要使用 datetime.strptimedateutil.parser 正确解析它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 2017-01-17
      相关资源
      最近更新 更多