【问题标题】:Iterating over a python array and find mean/min/max for 50 values遍历 python 数组并找到 50 个值的均值/最小值/最大值
【发布时间】:2020-04-02 12:09:16
【问题描述】:

我有一个数组,我想把它分成子数组。我需要知道前 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 循环来解决它,但我尝试的一切都失败了。

【问题讨论】:

    标签: python arrays numpy mean numpy-ndarray


    【解决方案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. ]])
    

    【讨论】:

      【解决方案2】:

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

      基本上,得到数组的长度,分割点,然后使用 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
      第 3 组:
      127.0
      154
      100

      希望对你有帮助!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-30
        • 2019-05-15
        • 2015-09-12
        • 1970-01-01
        • 2013-12-23
        • 2014-06-11
        • 2022-10-01
        • 2012-04-13
        相关资源
        最近更新 更多