Python中基于行输入的条件总和 [英] Conditional sum in Python based on row input

查看:71
本文介绍了Python中基于行输入的条件总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Python中进行条件求和。简化的思路如下:

I'm trying to do a conditional sum-product in Python. The simplified idea is as follows:

A = [1 1 2 3 3 3]
B = [0.50 0.25 0.99 0.80 0.70 0.20]

我想拥有输出

Total1 = 0.50*1 + 0.25*1
Total2 = 0.99*2
Total3 = 0.80*3 + 0.70*3 + 0.20*3

我在考虑使用FOR ... IF ...结构,以指定给定 A 中的值,应将 B 中的所有相应值相加。

I was thinking to use a FOR ... IF... structure, to specify that for a given value in A all corresponding values in B should be summed.

实际上这是一个庞大的数据集,所以我将不得不使脚本能够遍历所有类别?

In reality it's a huge dataset, so I will have to make the script capable to loop through all categories?

此刻,我正努力获取将该想法转换为适当的Python脚本。
有人可以指出我正确的方向吗?

At this moment I'm struggling to get the idea translated to an appropriate Python script. Can somebody point me to the right direction?

推荐答案

这似乎非常适合 itertools.groupby (假设 A 中的值被排序,对于 A = [1,1,2,2 ,1] ):

That seems like an excellent fit for itertools.groupby (assuming the values in A are sorted, it probably wouldn't work correctly for A=[1,1,2,2,1]):

from itertools import groupby
A = [1, 1, 2, 3, 3, 3]
B = [0.50, 0.25, 0.99, 0.80, 0.70, 0.20]

for key, grp in groupby(zip(A, B), key=lambda x: x[0]):
    grp = [i[1] for i in grp]
    print(key, key * sum(grp))

打印以下内容:

1 0.75
2 1.98
3 5.1

您也可以将其存储在列表中值的打印:

You could also store it in a list instead of printing the values:

res = []
for key, grp in groupby(zip(A, B), key=lambda x: x[0]):
    grp = [i[1] for i in grp]
    res.append(key*sum(grp))
print(res)
# [0.75, 1.98, 5.1]






如果您可能选择了第三方套餐,也可以使用 iteration_utilities.groupedby

>>> from iteration_utilities import groupedby
>>> from operator import itemgetter, add

>>> {key: key*sum(value) for key, value in groupedby(zip(A, B), key=itemgetter(0), keep=itemgetter(1)).items()}
{1: 0.75, 2: 1.98, 3: 5.1}

或使用减少 groupedby 的code>参数:

or using the reduce parameter of groupedby directly:

>>> groupedby(zip(A, B), key=itemgetter(0), keep=lambda x: x[0]*x[1], reduce=add)
{1: 0.75, 2: 1.98, 3: 5.1}

免责声明:我是 iteration_utilities 包。

Disclaimer: I'm the author of the iteration_utilities package.

这篇关于Python中基于行输入的条件总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆