遍历python数组并找到50个值的平均值/最小值/最大值

时间:2019-12-09 11:34:53

标签: python arrays mean

我是python编程的新手,所以希望我的问题很容易解决。我有一个数组,我有点想将其划分为子数组。我需要知道前50个值的平均值/最小值/最大值,然后是下一个值,依此类推。我想将平均值,最小值,最大值保存在另一个矩阵中。目前,我正在以这种方式解决它:

np.array([[a[0:50].mean(), a[0:50].min(), a[0:50].max()],
          [a[51:100].mean(), a[51:100].min(), a[51:100].max()],...])

a是矩阵。 现在,这适用于非常小的阵列,但是我需要用于更大的阵列。我当时正在考虑使用for或while循环来解决它,但是我尝试的所有方法都失败了。

感谢您的帮助!:)

2 个答案:

答案 0 :(得分:1)

使用array_split

a = np.array(range(200))

b = np.array([[x.mean(), x.min(), x.max()] 
              for x in np.array_split(a, a.shape[0]/50)])

输出:

>>> b
array([[ 24.5,   0. ,  49. ],
       [ 74.5,  50. ,  99. ],
       [124.5, 100. , 149. ],
       [174.5, 150. , 199. ]])

答案 1 :(得分:1)

这里不是完整的解决方案,但我的建议应该有所帮助。

基本上,获得数组的长度,分割点,然后使用np.split分隔它们。

    # get the length of the array, divide by 50.
    # converting to int so there's no decimals
    fifties = int(len(np.array) / 50)

    # convert this to an array to work through
    fifties = np.arange(fifties)

    # get the split points
    # this could be combined into the command above
    for i in fifties:
        fifties[i] = fifties[i] * 50

    # split the array per 50 into new arrays / dimensions on the array
    newarray = np.split(np.array,fifties)

    # iterate through each new array
    # len(newarray) gives the number of arrays, start at 1, not 0 though

    for i in range(1,len(newarray):
        print('Group '+str(i)+':')
        print(newarray[i].mean())
        print(newarray[i].min())
        print(newarray[i].max())

输出:

第1组:
24.5
49
0
第2组:
74.5
99
50
第三组:
127.0
154
100

我希望这会有所帮助!