如何使用numpy对每2个连续向量求和

2024-10-03 23:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用numpy对每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] 

Tags: innumpy示例列表fordefrange整数
2条回答

您可以将数组重塑为成对数组,这将允许您通过提供正确的轴直接使用np.sum()np.mean()

import numpy as np

a = np.array([[2,2], [1,2], [1,1], [2,2]]) 

np.sum(a.reshape(-1, 2, 2), axis=1)

# array([[3, 4],
#        [3, 3]])

编辑地址注释:

要获得每个相邻对的平均值,可以将原始数组的片相加,并将广播除以2:

> a = np.array([[2,2], [1,2], [1,1], [2,2], [11, 10], [20, 30]]) 

> (a[:-1] + a[1:])/2

array([[ 1.5,  2. ],
       [ 1. ,  1.5],
       [ 1.5,  1.5],
       [ 6.5,  6. ],
       [15.5, 20. ]])
 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()来完成。你知道吗

相关问题 更多 >