Itertools Groupby遍历不同的列 [英] Itertools Groupby looping over different columns
问题描述
试图在Python中执行条件求和积.简化的想法如下:
'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
感谢这里的人们的支持,这一部分工作了!
Thanks to the support by people over here, this part worked out!
我要添加的下一个功能是能够针对不同的列"B"(例如B1,B2,B3 ...)(具有不同的值)进行计算. 这些存储在Excel中,我用openpyxl将它们读出到不同的列表中(可能更有效...) 这意味着B1/B2/...中的值与A中的相应值相对应.
Next function I like to add, is being able to calculate this for different columns 'B' (say B1, B2, B3, ...) (with different values). These are stored in Excel and I read them out to different lists with openpyxl (can probably be more efficient...) This means the values in B1/B2/... are corresponding with the respective values in A.
number = -1
j = 0
for col in ws.iter_cols():
if col[3].value == "fast" :
number = j
j+=1
B1 = [row[number].value for row in ws.iter_rows(min_row=5, max_row=63332) ]
B1_float = [float(i) for i in B1]
是否可以执行将此脚本划分为不同的组合(A& B1/A& B2/A& B3/...)并将其存储在矩阵中? (或Excel文件)
Is there a way to perform this script to different combinations (A&B1 / A&B2 / A&B3 / ...) and store them in a matrix? (or excel file)
我希望我的意思很清楚,否则请让我知道!
I hope it's clear what I mean, if not, let me know!
推荐答案
您似乎在问两个问题:
- 根据单独列表中的组计算产品总和
- 将这些结果写入Excel文件
由于这些是完全不同的问题,因此我将解决第一个问题,并参考第二个问题.
As these are quite different problems, I will address the first and refer to references on the second.
import operator as op
import itertools as it
import functools as ft
A = [1, 1, 2, 3, 3, 3]
B = [0.5, 0.25, 0.99, 0.8, 0.7, 0.2]
groups = [list(g) for k, g in it.groupby(zip(A, B), op.itemgetter(0))]
groups
# [[(1, 0.5), (1, 0.25)], [(2, 0.99)], [(3, 0.8), (3, 0.7), (3, 0.2)]]
在这里,我们压缩数据列并根据列表A
将它们分组.现在,我们可以将适当的运算符应用于groups
中的每个可迭代项.
Here we zip the columns of data and group them according to list A
. Now we are able to apply the appropriate operators to each iterable in groups
.
[sum(ft.reduce(op.mul, i) for i in sub) for sub in groups]
# [0.75, 1.98, 5.1]
关于将数据写入Excel的方法,有几个Python库可用,每个库都包含有关文档怎么做.
As for writing data to Excel, there are several Python libraries available, each with documentation on how to do so.
这篇关于Itertools Groupby遍历不同的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!