如何根据索引添加子列表的元素 - Python

How to add the elements of sublists based on index - Python

sub-lists中的元素是如何根据values的索引添加的?比如这个怎么转:

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

进入这个? :

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

抱歉,如果标题不是很清楚,我真的不知道怎么写。

如果允许使用 NumPy,那么您可以使用 numpy.sum()axis=0:

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

另一方面,如果您想要一个简单的 Python 解决方案,那么使用 ziped 结果在列表理解中就足够了:

In [32]: [sum(l) for l in zip(*nested_list)]
Out[32]: [9, 12]

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