我有一个名为 MEL 的数据集,其形状为 (94824,),其中大多数实例的形状为 (99, 13),但有些实例的形状较小。它由( float )MEL 频率组成。我试图将所有值放入形状为 (94824, 99 , 13) 的空 numpy 矩阵中。所以有些实例留空。有什么建议吗?
MEL type = numpy.ndarray
for i in MEL type(i) = <class 'numpy.ndarray'>
for j in i type (j) = <class 'numpy.ndarray'>
最佳答案
由于您的 MEL
数组不是同质形状的,因此首先我们需要过滤掉形状相同的数组(即 (99, 13)
)。为此,我们可以使用:
filtered = []
for arr in MEL:
if arr.shape == (99, 13):
filtered.append(arr)
else:
continue
然后我们可以初始化一个数组来保存结果。然后我们可以迭代这个过滤后的数组列表并计算轴 1 上的平均值,如下所示:
averaged_arr = np.zeros((len(filtered), 99))
for idx, arr in enumerate(filtered):
averaged_arr[idx] = np.mean(arr, axis=1)
这应该计算出所需的矩阵。
<小时/>这里是一个重现您的设置的演示,假设所有数组具有相同的形状:
# inputs
In [20]: MEL = np.empty(94824, dtype=np.object)
In [21]: for idx in range(94824):
...: MEL[idx] = np.random.randn(99, 13)
# shape of the array of arrays
In [13]: MEL.shape
Out[13]: (94824,)
# shape of each array
In [15]: MEL[0].shape
Out[15]: (99, 13)
<小时/>
# to hold results
In [17]: averaged_arr = np.zeros((94824, 99))
# compute average
In [18]: for idx, arr in enumerate(MEL):
...: averaged_arr[idx] = np.mean(arr, axis=1)
# check the shape of resultant array
In [19]: averaged_arr.shape
Out[19]: (94824, 99)
关于python - 迭代 numpy 数组时求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732007/