繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM