python - 通过在 Python 中应用加权平均来聚合 bin 中的字典列表
问题描述
我有一个字典列表,如下所示:
_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
通过使用熊猫数据帧,我设法收到了结果,但是它们的性能太慢了(大约 0.5 秒)。在python中有没有快速的方法来做到这一点?
解决方案
不使用熊猫,自己做几乎是瞬间的:
result = []
cumulative_quantity = 0
bucket = {'price': 0.0, 'quantity': 0}
for dct in lst:
dct_quantity = dct['quantity'] # enables non-destructive decrementing
while dct_quantity > 0:
if bucket['quantity'] == 100:
bucket['cumulative_quantity'] = cumulative_quantity
result.append(bucket)
bucket = {'price': 0.0, 'quantity': 0}
added_quantity = min([dct_quantity, 100 - bucket['quantity']])
bucket['price'] = (bucket['price'] * bucket['quantity'] + dct['price'] * added_quantity) / (bucket['quantity'] + added_quantity)
dct_quantity -= added_quantity
bucket['quantity'] += added_quantity
cumulative_quantity += added_quantity
if bucket['quantity'] != 0:
bucket['cumulative_quantity'] = cumulative_quantity
result.append(bucket)
给
>>> result
[{'cumulative_quantity': 100, 'price': 7003.0, 'quantity': 100},
{'cumulative_quantity': 200, 'price': 7038.0, 'quantity': 100},
{'cumulative_quantity': 300, 'price': 7050.0, 'quantity': 100},
{'cumulative_quantity': 400, 'price': 7060.5, 'quantity': 100}]
这可以线性完成,如 O(p),其中 p 是零件数(相当于 O(n * k),其中 k 是每个 dict 必须分成的平均片段数(在您的示例中 k = 1.6) )。
推荐阅读
- objective-c - NSPopUpButton:NSPopUpButtonCell 已弃用?
- html - 导航栏中下拉菜单列表中的第二列
- rxjs - RxJs 热范围可观察
- sql - 将额外的条目移动到 SQL Server 中的新行
- c# - 编辑 ListView Xamarin.Forms 中各个行的文本颜色
- javascript - 如何创建循环以查看是否正确填写了所需的输入行
- sharepoint - 在现代网站中添加 SPFx webpart 时的 Javascript
- c# - 没有为此对象定义无参数构造函数 nopCommerce 4.0
- progressive-web-apps - 将谷歌应用脚本网络应用迁移到渐进式网络应用?
- vba - VBA:或操作员未执行