0

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

0

1 Answer 1

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.