如何根据值的索引在子列表中添加元素?例如,你怎么转这个:
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解决方案,那么在列表理解中使用zip
ed结果就足够了:
In [32]: [sum(l) for l in zip(*nested_list)]
Out[32]: [9, 12]
已经接受了答案,但以下内容也可以用于您的要求。让我知道这是否回答了您的问题。
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