Group by interval time

Peter Otten __peter__ at web.de
Thu Feb 12 08:29:59 EST 2015


charles.sartori at gmail.com wrote:

> Hello there!
> 
> I`m trying to group by a list of Row() objects in 12days interval and
> sum(). values. Here is an example of the list
> 
> [Row(time=datetime.datetime(2013, 1, 1, 0, 0), sum=4676557380615),
> [Row(time=datetime.datetime(2013, 1, 2, 0, 0), sum=6549630855895),
> [Row(time=datetime.datetime(2013, 1, 3, 0, 0), sum=6549630855895), ...]
> 
> Row() objects has two vars: row.time and row.sum
> 
> 
> The result that I`m looking for is:
> [[datetime.datetime(2013, 1, 1, 0, 0), value],
> [datetime.datetime(2013, 1, 12, 0, 0), value],
> [datetime.datetime(2013, 1, 24, 0, 0), value]
> ]
> Where value is the sum() of all row.sum in that interval.
> 
> I`m trying to use itertools.groupby by I could not get it to work yet.

If the data is sorted by time then you can use groupby, otherwise consider 
putting it into a (default)dict. Here is an example for both methods:

import datetime
import random
from itertools import groupby
from collections import defaultdict, namedtuple

BASEDATE = datetime.datetime(2015, 1, 1)
INTERVAL = 12 # time interval in days
DAYS = datetime.timedelta(days=INTERVAL)

def make_sample_rows():
    random.seed(42)
    Row = namedtuple("Row", "time sum")
    return [
        Row(BASEDATE + datetime.timedelta(days=random.randrange(-20, 80)),
            random.randrange(300))
        for i in range(30)]

def get_key(row):
    offset = (row.time - BASEDATE).days // INTERVAL
    return BASEDATE + datetime.timedelta(days=offset)

def format_time(time):
    return time.strftime("%Y-%m-%d")

if __name__ == "__main__":
    rows = make_sample_rows()

    # with groupby()
    for key, group in groupby(sorted(rows), key=get_key):
        print("{} - {}".format(format_time(key), format_time(key+DAYS)))
        print("-" * 23)

        group = list(group)
        for row in group:
            print("{} {:4}".format(format_time(row.time), row.sum))
        print("{:>15}".format("----"))
        print("{:15}".format(sum(row.sum for row in group)))
        print("")

    # with defaultdict
    d = defaultdict(int)
    for row in rows:
        d[get_key(row)] += row.sum

    for time, sum in sorted(d.items()):
        print("{} {:4}".format(format_time(time), sum))





More information about the Python-list mailing list