使用np.log(array)时忽略负值 [英] Ignoring negative values when using np.log(array)

查看:121
本文介绍了使用np.log(array)时忽略负值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取numpy数组中特定列的日志时,即 logSFROIIdC = np.log(data_dC [:, 9]),编译器将返回错误:

When taking the log of a specific column within a numpy array, i.e., logSFROIIdC = np.log(data_dC[:, 9]) the compiler returns the error:

-c:13: RuntimeWarning: divide by zero encountered in log.

现在,我知道为什么会发生这种情况,即log(-1)=数学错误.

Now, I know why this happens, i.e., log(-1) = Math Error.

但是,我希望能够调用某些内容或编写一些代码,然后跳过该数组中会导致此错误的任何值,然后完全忽略该行.允许该数据列再次可用.

However, I want to be able to call something or write some code which then skips any value in the array which would cause this error, then ignoring that row altogether. Allowing that data column to be usable again.

我尝试了各种方法,这是向社区提出的不得已的选择.

I have tried various methods and this is a last resort asking the community.

推荐答案

您可以使用

You can control this behavior with np.seterr. Here's an example.

首先,告诉numpy 忽略无效值:

First, tell numpy to ignore invalid values:

In [4]: old = np.seterr(invalid='ignore')

现在 log(-1)不会生成警告:

In [5]: x = np.array([-1.,1])

In [6]: np.log(x)
Out[6]: array([ nan,   0.])

还原以前的设置:

In [7]: np.seterr(**old)
Out[7]: {'divide': 'warn', 'invalid': 'ignore', 'over': 'warn', 'under': 'ignore'}

现在我们得到警告:

In [8]: np.log(x)
/Users/warren/anaconda/bin/ipython:1: RuntimeWarning: invalid value encountered in log
  #!/Users/warren/anaconda/python.app/Contents/MacOS/python
Out[8]: array([ nan,   0.])

还有一个上下文管理器, np.错误状态 .例如,

There is also a context manager, np.errstate. For example,

In [10]: with np.errstate(invalid='ignore'):
   ....:     y = np.log(x)
   ....:     

In [11]: y
Out[11]: array([ nan,   0.])

这篇关于使用np.log(array)时忽略负值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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