简体   繁体   English

如何基于索引添加子列表的元素-Python

[英]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.

相关问题 如何根据python3中的元素序列在列表中创建子列表? - How to create sublists within a list based on a sequence of elements in python3? Python-删除同一索引下的几个子列表的元素 - Python - Delete elements of several sublists at the same index 根据python中的条件索引添加子列表元素 - Adding sublists elements based on indexing by condition in python 如何首先基于初始列表的单个元素将列表拆分为子列表,然后仅在 python 中将列表的连续部分拆分为子列表? - How to split a list into sublists based on single elements of the initial list first and then contiguous portions of the list simply in python? 如何基于python嵌套列表中的公共元素计算子列表的数量? - How to count the number of sublists based on common elements from a nested list in python? 删除子列表中位于特定索引处的所有元素 - python 2 - remove all elements within sublists that are at a specific index - python 2 Python如何根据日期创建子列表? - Python how create sublists based by date? Python 根据列表元素第一个数字的相等性将列表分成子列表 - Python list into sublists based on the equality of first digit of the list elements 如何比较列表列表中 2 个子列表元素的索引 - How to compare the index of 2 sublists' elements from a list of lists 如何根据开始和结束元素从列表创建子列表? - How to create sublists from list based on start and end elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM