有没有更好的方法让 numpy.argmin() 忽略 NaN 值
我想获取包含 NaN 的 numpy 数组的最小值的索引,并且
>>> a = array([ nan, 2.5, 3., nan, 4., 5.])
>>> a
array([ NaN, 2.5, 3. , NaN, 4. , 5. ])
如果我运行 argmin,我希望忽略它们,它返回第一个 NaN 的索引
>>> a.argmin()
0
我用 Infs 替换 NaN,然后运行 argmin
>>> a[isnan(a)] = Inf
>>> a
array([ Inf, 2.5, 3. , Inf, 4. , 5. ])
>>> a.argmin()
1
我的困境是以下内容: 我不想将 NaN 更改为 Infs,然后在完成 argmin 后又返回(因为 NaN 稍后在代码中有意义)。有更好的方法吗?
还有一个问题,如果a的原始值全部都是NaN,结果应该是什么?在我的实现中答案是 0
I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored
>>> a = array([ nan, 2.5, 3., nan, 4., 5.])
>>> a
array([ NaN, 2.5, 3. , NaN, 4. , 5. ])
if I run argmin, it returns the index of the first NaN
>>> a.argmin()
0
I substitute NaNs with Infs and then run argmin
>>> a[isnan(a)] = Inf
>>> a
array([ Inf, 2.5, 3. , Inf, 4. , 5. ])
>>> a.argmin()
1
My dilemma is the following: I'd rather not change NaNs to Infs and then back after I'm done with argmin (since NaNs have a meaning later on in the code). Is there a better way to do this?
There is also a question of what should the result be if all of the original values of a are NaN? In my implementation the answer is 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然!使用
nanargmin
:还有
nansum
、nanmax
、nanargmax
和nanmin
,在
scipy.stats
中,有nanmean
和nanmedian
。了解更多方法忽略
nan
s,查看屏蔽数组。Sure! Use
nanargmin
:There is also
nansum
,nanmax
,nanargmax
, andnanmin
,In
scipy.stats
, there isnanmean
andnanmedian
.For more ways to ignore
nan
s, check out masked arrays.