亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

迭代 numpy 數組時求平均值

迭代 numpy 數組時求平均值

墨色風雨 2021-09-14 16:40:06
我有一個名為 MEL of shape (94824,) 的數據集,其中大多數實例的形狀為 (99, 13),但有些實例的形狀較小。它由(浮動)MEL 頻率組成。我試圖將所有值放入一個空的 numpy 形狀矩陣 (94824, 99, 13) 中。所以有些實例是空的。有什么建議?MEL type = numpy.ndarrayfor i in MEL type(i) = <class 'numpy.ndarray'>for j in i type (j) = <class 'numpy.ndarray'>
查看完整描述

1 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

由于您的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)


查看完整回答
反對 回復 2021-09-14
  • 1 回答
  • 0 關注
  • 211 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號