How can I reshape and aggregate list of tuples in Python?
Posted
by radek
on Stack Overflow
See other posts from Stack Overflow
or by radek
Published on 2010-05-15T19:25:14Z
Indexed on
2010/05/15
19:34 UTC
Read the original article
Hit count: 236
python
I'm a newb to Python so apologies in advance if my question looks trivial.
From a psycopg2 query i have a result in the form of a list of tuples looking like:
[(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)]
Each tuple represents id of a location where event happened and hour of the day when event took place.
I'd like to reshape and aggregate this list with subtotals for each hour in each location, to a form where it looks like:
[(1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 0), (2, 1, 1), (2, 3, 3)]
Where each touple will now tell me that, for example: in location 1, at hour 0 there were 2 events; in location 1, at hour 1 there was 1 event; and so on...
If there were 0 events at certain hour, I still would like to see it, as for example 0 events at 0 hours in location 2: (2, 0, 0)
How could I implement it in Python?
© Stack Overflow or respective owner