【发布时间】:2019-02-03 11:41:58
【问题描述】:
我有一个字典列表,如下所示:
_input = [{'cumulated_quantity': 30, 'price': 7000, 'quantity': 30},
{'cumulated_quantity': 80, 'price': 7002, 'quantity': 50},
{'cumulated_quantity': 130, 'price': 7010, 'quantity': 50},
{'cumulated_quantity': 330, 'price': 7050, 'quantity': 200},
{'cumulated_quantity': 400, 'price': 7065, 'quantity': 70}]
我想将字典分组到数量为 100 的箱中,其中价格计算为加权平均值。结果应如下所示:
result = [{'cumulated_quantity': 100, 'price': 7003, 'quantity': 100},
{'cumulated_quantity': 200, 'price': 7038, 'quantity': 100},
{'cumulated_quantity': 300, 'price': 7050, 'quantity': 100},
{'cumulated_quantity': 400, 'price': 7060.5, 'quantity': 100}]
结果字典中的加权平均值计算如下:
7003 = (30*7000+50*7002+20*7010)/100
7038 = (30*7010+70*7050)/100
7050 = 100*7050/100
7060.5 = (30*7050+70*7065)/100
通过使用 pandas 数据帧,我设法收到了结果,但是它们的性能太慢了(大约 0.5 秒)。在python中有没有快速的方法来做到这一点?
【问题讨论】:
-
如何定义垃圾箱?垃圾箱
'cumulated_quantity': 100是为'cumulated_quantity'<=100设计的吗? -
bin 大小是任意选择的,它将是一个变量。如果 cumulated_quantity
标签: python list dictionary weighted-average