2

How do you add the elements in sub-lists according to the index of the values? For example, how do you turn this:

nested_list = [[1,2],[3,4],[5,6]]

into this? :

sublist_sums = [9,12] # [1 + 3 + 5, 2 + 4 + 6]

Sorry if the title wasn't very clear, I wasn't really sure how to put it.

2 Answers 2

2

If using NumPy is allowed, then you can use numpy.sum() along axis=0:

In [11]: np.sum(nested_list, axis=0)
Out[11]: array([ 9, 12])

On the other hand, if you want a plain Python solution, then using ziped result in a list comprehension would suffice:

In [32]: [sum(l) for l in zip(*nested_list)]
Out[32]: [9, 12]
Sign up to request clarification or add additional context in comments.

2 Comments

I used a for loop to modify the elements of the list. Is there another, more Pythonic way of doing this?
@PandaTobi Added!
1

Already an answer is accepted , but the following can also be used for your requirement.Let me know does this answer your question.

import pandas as pd
import numpy as np

c = ['Val1','Val2'] 
v = [
        [1,1.0],
        [2,1.0],
        [1,1.0],
        [2,0.98],
        [3,0.78],
        [4,0.70],
        [9,0.97],
        [6,0.67],
        [12,0.75],

    ]



n = len(v)

df = pd.DataFrame(v,columns=c)


#Take top N ie all elements in this case and sum it.
print(list(df.groupby('Val1').head(n).sum()))  

#### Output ####
[40.0, 7.85]




#Alternatively you can create a column where the value is same for all
#In my case column is 'id' and value is 1
#Then apply group-by-sum on 'id'
df['id'] = [1]*n   
print(df.groupby('id').sum())

#### Output ####
    Val1  Val2
id            
1     40  7.85

1 Comment

Thank you Preetham, this is a nice alternative to kmario's answer. You deserve an upvote! :)

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.