我已经检查了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.]
答案 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.])