【问题标题】:Grouping Data by Search Algorithms按搜索算法分组数据
【发布时间】:2021-07-26 17:26:13
【问题描述】:

我有一个 Python 示例数据集,其中每条数据都有 3 个值:

[ 字符串日期,整数 24 小时时间(前两个数字 = 小时,后两个数字 = 分钟),整数持续时间(总是 15 分钟)]

我的目标是将具有相同日期、相邻 24 小时时间的数据片段分组。 24 小时时间值以 15 分钟间隔相邻。最终,将具有相邻时间的数据片段分组将导致持续时间增加,无论分组多少 15 分钟间隔。我在下面提供了列表final_dataset,以更好地表示最终数据集的外观。

我测试了一些代码以线性搜索initial_dataset。这是粗略的伪代码:

# -- Start at first data piece (call this previous)
    # -- Check next data piece (call this current)
    # -- Subtract 24hr time values for current and previous
    # -- If difference is 15, append to a separate list the combined data piece
         # Check next data piece (call this next)
         # Subtract 24hr time values for next and current
         # Repeat
                  # Check next data piece (call this next next)
                  # Repeat this linear iteration until the difference > 15
                  # Store last position of no adjacency
# -- Continue at the last position of no adjacency and repeat this entire process until end of initial_dataset is reached

通过数据结构或搜索算法,有没有更有效的方法来实现这一目标?

# -- Example Dataset
initial_dataset = [ ['July 26, 2021',  1000,  15],
                    ['July 26, 2021',  1015,  15],
                    ['July 26, 2021',  1030,  15],
                    ['July 26, 2021',  1045,  15],
                    ['July 26, 2021',  1500,  15],
                    ['July 27, 2021',  1400,  15], ]

final_dataset = [ ['July 26, 2021', 1000, 60], 
                  ['July 26, 2021', 1500, 15]
                  ['July 27, 2021', 1400, 15] ]

【问题讨论】:

    标签: python python-3.x algorithm search


    【解决方案1】:

    通过使用collections.defaultdict,分组时只需对数据进行一次传递:

    import collections
    data = [['July 26, 2021', 1000, 15], ['July 26, 2021', 1015, 15], ['July 26, 2021', 1030, 15], ['July 26, 2021', 1045, 15], ['July 26, 2021', 1500, 15], ['July 27, 2021', 1400, 15]]
    d = collections.defaultdict(dict)
    for a, b, c in data:
       if (v:=int(b/100)) in d[a]:
          d[a][v] += c
       else:
          d[a][v] = c
    
    result = [[a, j*100, k] for a, b in d.items() for j, k in b.items()]
    

    输出:

    [['July 26, 2021', 1000, 60], ['July 26, 2021', 1500, 15], ['July 27, 2021', 1400, 15]]
    

    【讨论】:

    • 有没有办法在 24 小时内不严格按 100 的倍数分组?而是每次使用不同的值,取决于有多少相邻的 24 小时时间?比如允许对['July 26, 2021', 1000, 75]进行分组?
    猜你喜欢
    • 2020-11-21
    • 2014-05-25
    • 2015-07-12
    • 1970-01-01
    • 2021-03-23
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多