Itertools Groupby Loops On Different Columns

'trying to make a conditional product-sum in Python. A simplified idea is this:

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

I would like to have a way out

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 of people here, this part has been developed!

The next function that I want to add can calculate this for different columns of "B" (say, B1, B2, B3, ...) (with different values). They are stored in Excel, and I read them in different lists using openpyxl (perhaps more efficient ...) This means that the values ​​in B1 / B2 / ... correspond to the corresponding 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]

Is there a way to execute this script for different combinations (A & B1 / A & B2 / A & B3 / ...) and save them in a matrix? (or excel file)

I hope it is clear what I mean, if not, let me know!

0
1

, :

  • Excel

, .

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.

[sum(ft.reduce(op.mul, i) for i in sub) for sub in groups]
# [0.75, 1.98, 5.1]

Excel, Python, , .

+1

Source: https://habr.com/ru/post/1683516/


All Articles