簡體   English   中英

如何在Python中重塑和匯總元組列表?

[英]How can I reshape and aggregate list of tuples in Python?

我是Python的新手,所以如果我的問題看起來很微不足道,請提前道歉。

從psycopg2查詢中,我得到的結果以元組列表的形式顯示,如下所示:

[(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)]

每個元組代表事件發生的位置的ID,以及事件發生的一天的時間。

我想將每個位置每小時的小計重塑並匯總此列表,使其看起來像這樣:

[(1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 0), (2, 1, 1), (2, 3, 3)]

現在每個小伙伴都會告訴我,例如:在位置1,在0小時有2個事件;在位置0,有2個事件。 在位置1,在第1小時有1個事件; 等等...

如果某個小時有0個事件,我仍然希望看到它,例如在位置2:(2,0,0)的0小時有0個事件。

我如何在Python中實現它?

編輯:感謝您的幫助!

就像是...:

import collections

raw_data = [(1, 0), (1, 0), (1, 1), (2, 1), (2, 2), (2, 2), (2, 2)]
aux = collections.defaultdict(int)
for x, y in raw_data:
  aux[x, y] += 1

locations = sorted(set(x for x, y in raw_data))
hours = sorted(set(y for x, y in raw_data))
result = [(x, y, aux[x, y]) for x in locations for y in hours]

如果您希望位置和時間反映原始數據中的內容。 如果您對位置和小時均應跨越的范圍具有獨立的信息,而與raw_data實際發生的任何時間和位置完全不同,則可能要對每個位置和小時使用range(some, thing)

如果要從數據庫中獲取此信息,為什么不首先進行查詢呢? 諸如: SELECT hour, location, COUNT(*) FROM events GROUP BY hour, location ORDER BY hour, location

在Python中,也許是這樣的:

timed_events = {}
# Count them up
for event in events_from_database:
    timed_events[event] = timed_events.setdefault(event, 0) + 1

# Form a new list with the original data plus the count
aggregate_list = [(evt[0], evt[1], count) for evt,count in events.items()]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM