如何对属于同一个键的所有值求和?

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

这是一种方法,假设您从 pandas 数据帧 df 开始。此解决方案具有 O(n log n) 复杂性。

product = df.groupby('Product Name')['Quantity'].sum().to_dict()

# {'a': 8, 'b': 2, 'c': 7}

您可以执行 groupby 操作,生成由 "Product Name" 索引的系列。然后用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}

既然你提到了 pandas

df.set_index('ProductName').Quantity.sum(level=0).to_dict()
Out[20]: {'a': 8, 'b': 2, 'c': 7}