如何使用 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] 
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()来完成。

您可以将数组重塑为对,这将允许您通过提供正确的轴直接使用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. ]])

最新更新