Home > database >  Sum of values based on list of values in python
Sum of values based on list of values in python

Time:08-24

I was trying to do a code and got stucked in here.Having a data frame as below:

data = {'Name1':['A', 'B', 'C', 'D','E','F','G','H'],'Name2':['B','C','D','E','F','G','H','D'],
        'sum':[12,10,5,5, 10,15,10,13]
       }
df = pd.DataFrame(data)
df

Have a list of elements as follows:

my_list=[[A,B],[F,G],[A,B,C],[A,B,C,D,E],[E,F,G]]

Need to find out the sum as follows:

[A,B]->12
[F,G]->15
[A,B,C]->[A,B] [B,C]->12 10=22
[A,B,C,D,E]->[A,B] [B,C] [C,D] [D,E]->12 10 5 5=32
[E,F,G]->[E,F] [F,G]->10 15=25

CodePudding user response:

Craft a Series for easy indexing and use a list comprehension:

my_list=[['A','B'],['F','G'],['A','B','C'],
         ['A','B','C','D','E'],['E','F','G']]

s = df.set_index(['Name1', 'Name2'])['sum']

out = [sum(s.get(x) for x in zip(l, l[1:])) for l in my_list]

output: [12, 15, 22, 32, 25]

intermediate:

[[s.get(x) for x in zip(l, l[1:])] for l in my_list]
# [[12], [15], [12, 10], [12, 10, 5, 5], [10, 15]]
  • Related