计算不同长度的阵列的平均值

hjw*_*ide 8 python arrays numpy mean

当它们可能有不同的长度时,是否可以计算多个阵列的平均值?我正在使用numpy.所以我要说:

numpy.array([[1, 2, 3, 4, 8],    [3, 4, 5, 6, 0]])
numpy.array([[5, 6, 7, 8, 7, 8], [7, 8, 9, 10, 11, 12]])
numpy.array([[1, 2, 3, 4],       [5, 6, 7, 8]])
Run Code Online (Sandbox Code Playgroud)

现在我想计算平均值,但忽略了"缺失"的元素(当然,我不能只是附加零,因为这会弄乱平均值)

有没有办法在不迭代数组的情况下执行此操作?

PS.这些数组都是2-D,但总是具有相同数量的坐标.即第一个数组是5和5,第二个是6和6,第三个是4和4.

一个例子:

np.array([[1, 2],    [3, 4]])
np.array([[1, 2, 3], [3, 4, 5]])
np.array([[7],       [8]])
Run Code Online (Sandbox Code Playgroud)

这必须给

(1+1+7)/3  (2+2)/2   3/1
(3+3+8)/3  (4+4)/2   5/1
Run Code Online (Sandbox Code Playgroud)

并以图形方式:

[1, 2]    [1, 2, 3]    [7]
[3, 4]    [3, 4, 5]    [8]
Run Code Online (Sandbox Code Playgroud)

现在想象一下,这些二维数组放在彼此的顶部,坐标重叠,有助于该坐标的平均值.

unu*_*tbu 8

numpy.ma.mean允许您计算非掩码数组元素的平均值.但是,要使用numpy.ma.mean,您必须首先将三个numpy数组合并为一个屏蔽数组:

import numpy as np
x = np.array([[1, 2], [3, 4]])
y = np.array([[1, 2, 3], [3, 4, 5]])
z = np.array([[7], [8]])

arr = np.ma.empty((2,3,3))
arr.mask = True
arr[:x.shape[0],:x.shape[1],0] = x
arr[:y.shape[0],:y.shape[1],1] = y
arr[:z.shape[0],:z.shape[1],2] = z
print(arr.mean(axis = 2))
Run Code Online (Sandbox Code Playgroud)

产量

[[3.0 2.0 3.0]
 [4.66666666667 4.0 5.0]]
Run Code Online (Sandbox Code Playgroud)


dsa*_*laj 8

我经常需要它来绘制不同长度的性能曲线的平均值。

绘制多条不同长度的曲线

用简单的函数解决了它(基于@unutbu 的回答):

def tolerant_mean(arrs):
    lens = [len(i) for i in arrs]
    arr = np.ma.empty((np.max(lens),len(arrs)))
    arr.mask = True
    for idx, l in enumerate(arrs):
        arr[:len(l),idx] = l
    return arr.mean(axis = -1), arr.std(axis=-1)

y, error = tolerant_mean(list_of_ys_diff_len)
ax.plot(np.arange(len(y))+1, y, color='green')
Run Code Online (Sandbox Code Playgroud)

因此,将该函数应用于上面绘制的曲线列表会产生以下结果:

不同长度的不同曲线的均值和标准差图