[英]How to sum all the values that belong to the same key?
我正在從數據庫中提取數據,並假設我有類似以下內容:
Product Name Quantity
a 3
a 5
b 2
c 7
我想根據產品名稱總結數量,所以這就是我想要的:
product = {'a':8, 'b':2, 'c':7 }
這是從數據庫中獲取數據后要執行的操作:
for row in result:
product[row['product_name']] += row['quantity']
但這會給我:'a'= 5,而不是8。
選項1:熊貓
假設您以pandas
數據框df
開始,這是一種方法。 該解決方案具有O(n log n)復雜度。
product = df.groupby('Product Name')['Quantity'].sum().to_dict()
# {'a': 8, 'b': 2, 'c': 7}
這個想法是您可以執行groupby
操作,該操作將產生一個以“產品名稱”為索引的系列。 然后使用to_dict()
方法轉換為字典。
選項2:collections.Counter
如果從結果列表或迭代器開始,並希望使用for
循環,則可以使用collections.Counter
來解決O(n)的復雜性。
from collections import Counter
result = [['a', 3],
['a', 5],
['b', 2],
['c', 7]]
product = Counter()
for row in result:
product[row[0]] += row[1]
print(product)
# Counter({'a': 8, 'c': 7, 'b': 2})
選項3:itertools.groupby
您還可以將字典理解與itertools.groupby
。 這需要事先排序。
from itertools import groupby
res = {i: sum(list(zip(*j))[1]) for i, j in groupby(sorted(result), key=lambda x: x[0])}
# {'a': 8, 'b': 2, 'c': 7}
如果您堅持使用循環,則可以執行以下操作:
# fake data to make the script runnable
result = [
{'product_name': 'a', 'quantity': 3},
{'product_name': 'a', 'quantity': 5},
{'product_name': 'b', 'quantity': 2},
{'product_name': 'c', 'quantity': 7}
]
# solution with defaultdict and loops
from collections import defaultdict
d = defaultdict(int)
for row in result:
d[row['product_name']] += row['quantity']
print(dict(d))
輸出:
{'a': 8, 'b': 2, 'c': 7}
使用tuple
存儲結果。
編輯:
不清楚所提到的數據是否真的是數據幀。
如果是,則li = [tuple(x) for x in df.to_records(index=False)]
li = [('a', 3), ('a', 5), ('b', 2), ('c', 7)]
d = dict()
for key, val in li:
val_old = 0
if key in d:
val_old = d[key]
d[key] = val + val_old
print(d)
{'a': 8, 'b': 2, 'c': 7}
既然你提到熊貓
df.set_index('ProductName').Quantity.sum(level=0).to_dict()
Out[20]: {'a': 8, 'b': 2, 'c': 7}
從product左聯接QUANTITY GROUP BY產品名中選擇product_name,SUM(數量)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.