import numpy as np
import random
aa = np.random.rand(20,20)
aa[aa<0.5] = np.NaN
aa[aa>0.8] = np.NaN
我在最后一行代码中收到警告:
RuntimeWarning: invalid value encountered in greater
这是一个合法的警告吗?如何修复/避免它?
答案 0 :(得分:1)
在我的版本中,2个掩码运行良好:
In [388]: aa = np.random.rand(20,20)
In [389]: aa[aa<0.5]=np.NaN
In [390]: np.isnan(aa).sum()
Out[390]: 203
In [391]: aa[aa>0.8]=np.NaN
In [392]: np.isnan(aa).sum()
Out[392]: 279
In [393]: np.__version__
Out[393]: '1.11.2'
In [394]:
但是如果它确实给出了错误,我可以通过创建一个掩码并将其应用一次来绕过它:
In [394]: aa = np.random.rand(20,20)
In [395]: mask = (aa<0.5)|(aa>0.8)
In [396]: aa[mask]=np.nan
In [397]: np.isnan(aa).sum()
Out[397]: 280
答案 1 :(得分:0)
您是否尝试使用np.NaN替换小于阈值的值?如果是这样,那么你可以在其他选项中使用它。
import random
a = np.random.rand(5,5)*10
b = np.where(a < 5, np.NaN, a)
[[ 2.334 5.423 4.093 5.061 4.724]
[ 0.565 0.549 1.228 5.686 5.660]
[ 0.235 2.560 3.253 9.910 4.977]
[ 2.750 4.553 8.291 4.013 6.825]
[ 8.261 9.474 6.319 8.630 5.207]]
[[ nan 5.423 nan 5.061 nan]
[ nan nan nan 5.686 5.660]
[ nan nan nan 9.910 nan]
[ nan nan 8.291 nan 6.825]
[ 8.261 9.474 6.319 8.630 5.207]]