非零值的整数平均值 [英] Numpy mean of nonzero values

查看:83
本文介绍了非零值的整数平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为N * M的矩阵,我想找到每一行的平均值.值是从1到5,并且没有任何值的条目设置为0.但是,当我想使用以下方法查找均值时,它给了我错误的均值,因为它还计算了具有值的条目0.

I have a matrix of size N*M and I want to find the mean value for each row. The values are from 1 to 5 and entries that do not have any value are set to 0. However, when I want to find the mean using the following method, it gives me the wrong mean as it also counts the entries that have value of 0.

matrix_row_mean= matrix.mean(axis=1)

如何获取非零值的均值?

How can I get the mean of only nonzero values?

推荐答案

获取每一行中非零的计数,并将其用于平均每一行的总和.因此,实现看起来像这样-

Get the count of non-zeros in each row and use that for averaging the summation along each row. Thus, the implementation would look something like this -

np.true_divide(matrix.sum(1),(matrix!=0).sum(1))

如果您使用的是较旧版本的NumPy,则可以使用计数的浮点转换来替换np.true_divide,就像这样-

If you are on an older version of NumPy, you can use float conversion of the count to replace np.true_divide, like so -

matrix.sum(1)/(matrix!=0).sum(1).astype(float)

样品运行-

In [160]: matrix
Out[160]: 
array([[0, 0, 1, 0, 2],
       [1, 0, 0, 2, 0],
       [0, 1, 1, 0, 0],
       [0, 2, 2, 2, 2]])

In [161]: np.true_divide(matrix.sum(1),(matrix!=0).sum(1))
Out[161]: array([ 1.5,  1.5,  1. ,  2. ])


解决问题的另一种方法是用NaNs替换零,然后使用np.nanmean,这将忽略那些NaNs而实际上是那些原始的zeros,就像-


Another way to solve the problem would be to replace zeros with NaNs and then use np.nanmean, which would ignore those NaNs and in effect those original zeros, like so -

np.nanmean(np.where(matrix!=0,matrix,np.nan),1)

从性能的角度来看,我建议使用第一种方法.

From performance point of view, I would recommend the first approach.

这篇关于非零值的整数平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆