![](/img/trans.png)
[英]Count the number of dict elements in Pandas column containing a list of dictionaries
[英]How can I count the number of elements given to a column sum from a list of dictionaries quickly?
呼! 这个头衔是满口的。
我有一个字典列表,从中我试图提取以下内容:
for code in codes:
for type in types:
for color in colors:
count = sum(1 for d in data if d.get('code') == code and d.get('type') == type and d.get('color') == color)
amount = sum(d.get('amount') for d in data if d.get('code') == code and d.get('type') == type and d.get('color') == color)
cost = sum(d.get('cost') for d in data if d.get('code') == code and d.get('type') == type and d.get('color') == color)
我知道我可以将最后两行更改为:
tally = {k: sum(d.get(k) for d in data if d.get('code') == code and d.get('type') == type and d.get('color') == color) for k in ('amount', 'cost')}
但是上面的行中是否也包含计数?
您可以在此处使用条件表达式 :
tally = {k: sum(d.get(k) if k != 'count' else 1 for d in data if d.get('code') == code and d.get('type') == type and d.get('color') == color) for k in ('count', 'amount', 'cost')}
我不会为每个(代码,类型,颜色)组合拖曳d,而是将它传递一次并存储结果:
from collections import defaultdict
counts = defaultdict(int)
amounts = defaultdict(float)
costs = defaultdict(float)
for d in data:
code = d.get('code')
type = d.get('type')
color = d.get('color')
if code in codes and type in types and color in colors:
key = (code, type, color)
counts [key] += 1
amounts[key] += d.get('amount')
costs [key] += d.get('cost')
为了获得最大速度,代码,类型和颜色应分别是集合或字典的键。
考虑到这里的嵌套循环是三重嵌套,我认为值得索引字典列表:
from collections import defaultdict
data_entries = defaultdict(list)
for d in data:
data_entries[(d['code'], d['type'], d['color'])].append(d)
for code in codes:
for type in types:
for color in colors:
entries = data_entries[(code, type, color)]
count = len(entries)
amount = sum(d.get('amount', 0) for d in entries)
cost = sum(d.get('cost', 0) for d in entries)
然后,您也可以使用Ashwini Chaudhary的答案中的条件表达式,但是当您只需要对实际匹配的条目求和时,它应该会明显更快。 tally['count'] = len(entries)
应该比dict理解要快,但是确实需要更多的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.