本文介紹了在矩陣中使用 numpy.sum 和 numpy.mean 時如何忽略值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在 numpy 中應用 sum 和 mean 時有沒有辦法避免使用特定值?
Is there a way to avoid using specific values when applying sum and mean in numpy?
例如,我想在計算結(jié)果時避免使用 -999 值.
I'd like to avoid, for instance, the -999 value when calculating the result.
In [14]: c = np.matrix([[4., 2.],[4., 1.]])
In [15]: d = np.matrix([[3., 2.],[4., -999.]])
In [16]: np.sum([c, d], axis=0)
Out[16]:
array([[ 7., 4.],
[ 8., -998.]])
In [17]: np.mean([c, d], axis=0)
Out[17]:
array([[ 3.5, 2. ],
[ 4. , -499. ]])
推薦答案
使用掩碼數(shù)組:
>>> c = np.ma.array([[4., 2.], [4., 1.]])
>>> d = np.ma.masked_values([[3., 2.], [4., -999]], -999)
>>> np.ma.array([c, d]).sum(axis=0)
masked_array(data =
[[7.0 4.0]
[8.0 1.0]],
mask =
[[False False]
[False False]],
fill_value = 1e+20)
>>> np.ma.array([c, d]).mean(axis=0)
masked_array(data =
[[3.5 2.0]
[4.0 1.0]],
mask =
[[False False]
[False False]],
fill_value = 1e+20)
這篇關(guān)于在矩陣中使用 numpy.sum 和 numpy.mean 時如何忽略值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!