平均值,nanmean和警告:空切片的平均值 [英] mean, nanmean and warning: Mean of empty slice

查看:1652
本文介绍了平均值,nanmean和警告:空切片的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我构造了两个numpy数组:

Say I construct two numpy arrays:

a = np.array([np.NaN, np.NaN])
b = np.array([np.NaN, np.NaN, 3])

现在我发现np.mean对于ab均返回nan:

Now I find that np.mean returns nan for both a and b:

>>> np.mean(a)
nan
>>> np.mean(b)
nan

自从numpy 1.8(2016年4月20日发布)以来,我们一直很幸运 nanmean ,它将忽略nan值:

Since numpy 1.8 (released 20 April 2016), we've been blessed with nanmean, which ignores nan values:

>>> np.nanmean(b)
3.0

但是,当数组没有 nan个值时,它会发出警告:

However, when the array has nothing but nan values, it raises a warning:

>>> np.nanmean(a)
nan
C:\python-3.4.3\lib\site-packages\numpy\lib\nanfunctions.py:598: RuntimeWarning: Mean of empty slice
  warnings.warn("Mean of empty slice", RuntimeWarning)

我不喜欢抑制警告;在没有该警告的情况下,我可以使用更好的功能来获得nanmean的行为吗?

I don't like suppressing warnings; is there a better function I can use to get the behaviour of nanmean without that warning?

推荐答案

我真的看不出有什么理由不只是抑制警告.

I really can't see any good reason not to just suppress the warning.

最安全的方法是使用 warnings.catch_warnings 上下文管理器仅在您预期警告发生的地方禁止显示该警告-这样,您就不会错过任何可能在代码的其他部分意外引发的其他RuntimeWarnings

The safest way would be to use the warnings.catch_warnings context manager to suppress the warning only where you anticipate it occurring - that way you won't miss any additional RuntimeWarnings that might be unexpectedly raised in some other part of your code:

import numpy as np
import warnings

x = np.ones((1000, 1000)) * np.nan

# I expect to see RuntimeWarnings in this block
with warnings.catch_warnings():
    warnings.simplefilter("ignore", category=RuntimeWarning)
    foo = np.nanmean(x, axis=1)

@dawg的解决方案也可以使用,但是最终为避免在所有NaN的数组上计算np.nanmean所必须采取的任何其他步骤将招致一些额外的开销,您可以通过抑制警告来避免这些开销.您的意图也将在代码中更加清晰地体现出来.

@dawg's solution would also work, but ultimately any additional steps that you have to take in order to avoid computing np.nanmean on an array of all NaNs are going to incur some extra overhead that you could avoid by just suppressing the warning. Also your intent will be much more clearly reflected in the code.

这篇关于平均值,nanmean和警告:空切片的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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