简体   繁体   English

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

[英]How to sum all the values that belong to the same key?

I'm pulling data from the database and assuming i have something like this: 我正在从数据库中提取数据,并假设我有类似以下内容:

    Product Name    Quantity
    a               3
    a               5
    b               2
    c               7

I want to sum the Quantity based on Product name, so this is what i want: 我想根据产品名称总结数量,所以这就是我想要的:

    product = {'a':8, 'b':2, 'c':7 }

Here's what I'm trying to do after fetching the data from the database: 这是从数据库中获取数据后要执行的操作:

    for row in result:
       product[row['product_name']] += row['quantity']

but this will give me: 'a'=5 only, not 8. 但这会给我:'a'= 5,而不是8。

Option 1: pandas 选项1:熊猫

This is one way, assuming you begin with a pandas dataframe df . 假设您以pandas数据框df开始,这是一种方法。 This solution has O(n log n) complexity. 该解决方案具有O(n log n)复杂度。

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

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

The idea is you can perform a groupby operation, which produces a series indexed by "Product Name". 这个想法是您可以执行groupby操作,该操作将产生一个以“产品名称”为索引的系列。 Then use the to_dict() method to convert to a dictionary. 然后使用to_dict()方法转换为字典。

Option 2: collections.Counter 选项2:collections.Counter

If you begin with a list or iterator of results, and wish to use a for loop, you can use collections.Counter for O(n) complexity. 如果从结果列表或迭代器开始,并希望使用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})

Option 3: itertools.groupby 选项3:itertools.groupby

You can also use a dictionary comprehension with itertools.groupby . 您还可以将字典理解与itertools.groupby This requires sorting beforehand. 这需要事先排序。

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}

If you insist on using loops, you can do this: 如果您坚持使用循环,则可以执行以下操作:

# 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))

The output: 输出:

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

Use tuple to store the result. 使用tuple存储结果。

Edit: 编辑:


Not clear if the data mentioned is really a dataframe. 不清楚所提到的数据是否真的是数据帧。

If yes then li = [tuple(x) for x in df.to_records(index=False)] 如果是,则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)

Output 输出量

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

Since you mention pandas 既然你提到熊猫

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