表示每一行非零值,并避免RuntimeWarning和NaN,因为有些行都为零

时间:2017-10-22 09:07:11

标签: python-2.7 numpy mean

我已经检查了Numpy mean of nonzero values并且效果很好。但是,我的矩阵的某些行都是零元素。在这种情况下,避免RuntimeWarning: invalid value encountered in true_divide的好方法是什么?此外,我不希望零元素在此处被Nan替换。

eachPSM = np.ones([3,4])
eachPSM[0] = 0
print eachPSM
>> [[ 0.  0.  0.  0.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
print np.true_divide(eachPSM.sum(1),(eachPSM!=0).sum(1))
>> RuntimeWarning: invalid value encountered in true_divide
[ nan   1.   1.]

4 个答案:

答案 0 :(得分:2)

使用a作为输入数组,您可以使用masking -

invalid_val = np.nan # specifies mean value to be assigned for all zeros rows
out = np.full(a.shape[0],invalid_val)
count = (a!=0).sum(1)
valid_mask = count!=0
out[valid_mask] = a[valid_mask].sum(1)/count[valid_mask]

答案 1 :(得分:0)

import warnings
...
with warnings.catch_warnings():
  warnings.simplefilter("ignore", category=RuntimeWarning)

eachPSM[np.isnan(eachPSM)] = 0

答案 2 :(得分:0)

因为除以1的任何东西与分子相同,你可以用1填充零,即

x = eachPSM.sum(1)
y = (eachPSM!=0).sum(1)
y[y==0] =  1 
np.true_divide(x,y)

#array([ 0.,  1.,  1.])

答案 3 :(得分:0)

蒙面阵列提供了优雅的解决方案:

eachPSM = np.ones([3,4])
eachPSM[0] = 0
eachPSM[1,1] = 0

#[[ 0.  0.  0.  0.]
# [ 1.  0.  1.  1.]
# [ 1.  1.  1.  1.]]

In [39]: np.ma.masked_equal(eachPSM,0).mean(1)
Out[39]: 
masked_array(data = [-- 1.0 1.0],
             mask = [ True False False],
       fill_value = 1e+20)

In [40]: np.ma.masked_equal(eachPSM,0).mean(1).data
Out[40]: array([ 0.,  1.,  1.])