[英]How to add the elements of sublists based on index - Python
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. 抱歉,标题不太清楚,我不确定如何放置。
If using NumPy is allowed, then you can use numpy.sum()
along axis=0
: 如果允许使用NumPy,则可以沿
axis=0
使用numpy.sum()
:
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 zip
ed result in a list comprehension would suffice: 另一方面,如果您想使用普通的Python解决方案,则在列表理解中使用
zip
ed结果就足够了:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.