![](/img/trans.png)
[英]Counting non-zero elements within each row and within each column of a 2D NumPy array
[英]An efficient way to calculate the mean of each column or row of non-zero elements
我有一個numpy數組用於電影用戶給出的評級。 評級介於1和5之間,而0表示用戶不對電影評分。 我想計算每部電影的平均評分,以及每個用戶的平均評分。 換句話說,我將計算每列或一行非零元素的平均值。
是否有一個高效的numpy數組函數來處理這種情況? 我知道按列或行手動迭代評級可以解決問題。
提前致謝!
由於要丟棄的值為0,您可以通過沿軸進行求和然后除以非零元素的數量(沿同一軸)手動計算平均值:
a = np.array([[8.,9,7,0], [0,0,5,6]])
a.sum(1)/(a != 0).sum(1)
結果是:
array([ 8. , 5.5])
正如您所看到的,零不被視為平均值。
在將所有0
值轉換為np.nanmean
之后,您可以使用np.nan
。 請注意, np.nanmean
僅適用於numpy 1.8
。
import numpy as np
ratings = np.array([[1,4,5,0],
[2,0,3,0],
[4,0,0,0]], dtype=np.float)
def get_means(ratings):
ratings[np.where(ratings == 0)] = np.nan
user_means = np.nanmean(ratings, axis=1)
movie_means = np.nanmean(ratings, axis=0)
return {'user_means' : user_means, 'movie_means' : movie_means}
結果:
>>> get_means(ratings)
{'movie_means': array([ 2.33333333, 4. , 4. , nan]),
'user_means': array([ 3.33333333, 2.5 , 4. ])}
另一種方法是使用屏蔽數組,屏蔽0值。 例如(使用@ Akavali的示例數據):
In [30]: ratings = np.array([[1,4,5,0],
....: [2,0,3,0],
....: [4,0,0,0]], dtype=np.float)
使用ratings==0
作為掩碼創建蒙版的ratings
:
In [31]: mratings = np.ma.masked_array(ratings, mask=ratings==0)
In [32]: mratings
Out[32]:
masked_array(data =
[[1.0 4.0 5.0 --]
[2.0 -- 3.0 --]
[4.0 -- -- --]],
mask =
[[False False False True]
[False True False True]
[False True True True]],
fill_value = 1e+20)
現在計算每個軸的平均值:
In [33]: mratings.mean(axis=0)
Out[33]:
masked_array(data = [2.3333333333333335 4.0 4.0 --],
mask = [False False False True],
fill_value = 1e+20)
In [34]: mratings.mean(axis=1)
Out[34]:
masked_array(data = [3.3333333333333335 2.5 4.0],
mask = [False False False],
fill_value = 1e+20)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.