在一周内迭代一分钟的间隔

时间:2015-05-14 11:50:19

标签: python iterator itertools

我希望在一周内生成一个矩阵,并以分钟为单位设置指定的间隔。每个单元格将根据对象列表计算,这些对象包含日期时间和值。如果没有日期时间与单元格匹配的对象,则该单元格应设置为0.例如,使用下面示例中显示的记录240分钟的间隔将生成以下矩阵:

day,section,output
0,0,0
0,1,0
0,2,6
0,3,0
0,4,39
0,5,0
1,0,0
1,1,0
1,2,-6
1,3,0
1,4,0
1,5,0
2,0,0
2,1,0
2,2,0
2,3,0
2,4,0
2,5,0
3,0,0
3,1,0
3,2,0
3,3,9
3,4,0
3,5,0
4,0,0
4,1,0
4,2,0
4,3,0
4,4,0
4,5,60
5,0,0
5,1,0
5,2,0
5,3,0
5,4,0
5,5,0
6,0,0
6,1,0
6,2,0
6,3,0
6,4,0
6,5,0

我已经在下面举了一个例子,说明如果只是每天完成而不将空单元格设置为0,它是如何天真地完成的。

import itertools
import datetime as dt

def _group_date(records, _fun):
    for _, chunk in itertools.groupby(records, key=lambda r: _fun(r.datetime)):
        yield chunk


class Record(object):
    def __init__(self, value, datetime):
        self.value = value
        self.datetime = datetime

if __name__ == '__main__':

    operator_func = lambda val: val*3
    min_interval  = 240    

    records = [Record(value=2, datetime=dt.datetime(2015, 1, 5, 8, 12)),
               Record(value=13,datetime=dt.datetime(2015, 1, 5, 17, 14)),
               Record(value=-2,datetime=dt.datetime(2015, 1, 6, 10, 27)),
               Record(value=5, datetime=dt.datetime(2015, 1, 8, 14, 1)),
               Record(value=-2, datetime=dt.datetime(2015, 1, 8, 15, 37)),
               Record(value=20,datetime=dt.datetime(2015, 1, 9, 20, 53))]

    # example just to show how it could be done naively if it was simply on a daily basis
    # without setting empty cells to 0
    day_records   = _group_date(records, lambda d: d.isocalendar()[2])
    output        = []
    for day in day_records:
        day_output = 0
        for rec in list(day):
            day_output = day_output + operator_func(rec.value)
        output.append(day_output)

    print output

这必须在特定环境中运行,该环境只有核心软件包。可悲的是没有熊猫或笨蛋。它必须运行~100M这些类对象(比这个MWE更复杂),因此效率也有些重要,但是获得简单运行的东西是最重要的。

0 个答案:

没有答案