迭代 numpy 数组时求平均值

我有一个名为 MEL of shape (94824,) 的数据集,其中大多数实例的形状为 (99, 13),但有些实例的形状较小。它由(浮动)MEL 频率组成。我试图将所有值放入一个空的 numpy 形状矩阵 (94824, 99, 13) 中。所以有些实例是空的。有什么建议?


MEL type = numpy.ndarray

for i in MEL type(i) = <class 'numpy.ndarray'>

for j in i type (j) = <class 'numpy.ndarray'>


墨色风雨
浏览 193回答 1
1回答

萧十郎

由于您的MEL数组不是均匀形状,首先我们需要过滤掉形状常见的数组(即(99, 13))。为此,我们可以使用:filtered = []for arr in MEL:&nbsp; &nbsp; if arr.shape == (99, 13):&nbsp; &nbsp; &nbsp; &nbsp; filtered.append(arr)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; continue然后我们可以初始化一个数组来保存结果。然后我们可以迭代这个过滤后的数组列表并计算轴 1 上的平均值,如:averaged_arr = np.zeros((len(filtered), 99))for idx, arr in enumerate(filtered):&nbsp; &nbsp; averaged_arr[idx] = np.mean(arr, axis=1)这应该计算所需的矩阵。这是一个重现您的设置的演示,假设所有数组都具有相同的形状:# inputs&nbsp;In [20]: MEL = np.empty(94824, dtype=np.object)In [21]: for idx in range(94824):&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp;MEL[idx] = np.random.randn(99, 13)# shape of the array of arraysIn [13]: MEL.shapeOut[13]: (94824,)# shape of each arrayIn [15]: MEL[0].shapeOut[15]: (99, 13)# to hold resultsIn [17]: averaged_arr = np.zeros((94824, 99))# compute averageIn [18]: for idx, arr in enumerate(MEL):&nbsp; &nbsp; ...:&nbsp; &nbsp; &nbsp;averaged_arr[idx] = np.mean(arr, axis=1)# check the shape of resultant arrayIn [19]: averaged_arr.shapeOut[19]: (94824, 99)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python