子数组中元素的平均值

问题描述 投票:0回答:4

我有一个像

a=[1, 2, 3, 4, 5, 6, 7]
这样的数组。我想把这个数组分成 3 个任意大小的块。

当我将其分成 3 个块时,我得到 3 个子数组:

[array([1, 2, 3]), array([4, 5]), array([6, 7])]

我的目标是获得一个具有子数组中元素平均值的数组:

[2, 4.5, 6.5]
,因为
(1+2+3)/3=2
(第一个元素),
(4+5)/2=4.5
(第二个元素),依此类推。

我尝试了以下代码:

import numpy as np
a=[1, 2, 3, 4, 5, 6, 7]
a_split=np.array_split(a, 3)
a_split_avg=np.mean(a_split, axis=1)

我收到以下错误:

tuple index out of range

python arrays numpy split average
4个回答
4
投票

这是一个矢量化解决方案,可以避免分割步骤以获得性能并直接获得分组求和,从而获得平均值 -

def average_groups(a, N): # N is number of groups and a is input array
    n = len(a)
    m = n//N
    w = np.full(N,m)
    w[:n-m*N] += 1
    sums = np.add.reduceat(a, np.r_[0,w.cumsum()[:-1]])
    return np.true_divide(sums,w)

样品运行 -

In [357]: a=[1, 2, 3, 4, 5, 6, 7]

In [358]: average_groups(a, N=3)
Out[358]: array([2. , 4.5, 6.5])

3
投票

您收到错误是因为

np.array_split
返回 numpy 数组的 python 列表,而不是多维 numpy 数组,因此
axis
无法使用它。将最后一行替换为:

a_split_avg = [np.mean(arr) for arr in a_split]

3
投票

您可以在计算中使用

np.vectorize
mean
函数应用于数组列表中的每个项目:

means = np.vectorize(np.mean)(a_split)

结果是一个列表,其中包含您创建的每个子数组的平均值。


0
投票

试试这个:

In [1224]: mean_arr = []
In [1225]: for i in a_split:
      ...:     mean_arr.append(np.mean(i))
      
In [1226]: 

In [1226]: mean_arr
Out[1226]: [2.0, 4.5, 6.5]

或使用

List Comprehensions
:

In [6]: mean_arr = [np.mean(i) for i in a_split]

In [7]: mean_arr
Out[7]: [2.0, 4.5, 6.5]
© www.soinside.com 2019 - 2024. All rights reserved.