首页 > 解决方案 > 如何使用numpy对每2个连续向量求和

问题描述

如何使用 numpy 对每 2 个连续向量求和。或每 2 个连续向量的平均值。列表列表(可以有偶数或奇数个向量。)示例:

[[2,2], [1,2], [1,1], [2,2]] --> [[3,4], [3,3]]

也许像这样,但使用 numpy 和实际适用于向量数组而不是整数数组的东西。或者如果存在的话,可能是某种数组理解。

def pairwiseSum(lst, n): 
    sum = 0; 
    for i in range(len(lst)-1):           
        # adding the alternate numbers 
        sum = lst[i] + lst[i + 1] 

标签: pythonpython-3.xnumpy

解决方案


 def mean_consecutive_vectors(lst, step):
    idx_list = list(range(step, len(lst), step))
    new_lst = np.split(lst, idx_list)
    return np.mean(new_lst, axis=1)

也可以用np.sum()代替来完成np.mean()


推荐阅读