在Python中使用numpy/scipy忽略数组中的-Inf值 [英] Ignoring -Inf values in arrays using numpy/scipy in Python

查看:563
本文介绍了在Python中使用numpy/scipy忽略数组中的-Inf值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy的NxM数组,我想记录该日志,并忽略在记录之前为负数的条目.当我获取否定条目的日志时,它返回-Inf,因此,我将得到一个带有一些-Inf值的矩阵.然后,我想对这个矩阵的各列求和,但忽略了-Inf值-我该怎么做?

I have an NxM array in numpy that I would like to take the log of, and ignore entries that were negative prior to taking the log. When I take the log of negative entries, it returns -Inf, so I will have a matrix with some -Inf values as a result. I then want to sum over the columns of this matrix, but ignoring the -Inf values -- how can I do this?

例如,

mylogarray = log(myarray)
# take sum, but ignore -Inf?
sum(mylogarray, 0)

我知道有nansum,我需要等价的东西,例如infsum.

I know there's nansum and I need the equivalent, something like infsum.

谢谢.

推荐答案

使用掩码数组 :

>>> a = numpy.array([2, 0, 1.5, -3])
>>> b = numpy.ma.log(a)
>>> b
masked_array(data = [0.69314718056 -- 0.405465108108 --],
             mask = [False  True False  True],
       fill_value = 1e+20)

>>> b.sum()
1.0986122886681096

这篇关于在Python中使用numpy/scipy忽略数组中的-Inf值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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