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
Alternative to using masked arrays....
import numpy as np
myarray = np.array([2, 0, 1.5, -3])
mylogarray = np.log(myarray) # The log of negative numbers is nan, 0 is -inf
summed = mylogarray[np.isfinite(mylogarray)].sum() # isfinite will exclude inf and nan
print(f'Sum of logged array is: {summed}')
>>> Sum of logged array is: 1.0986122886681096
Use a filter()
:
>>> array
array([ 1., 2., 3., -Inf])
>>> sum(filter(lambda x: x != float('-inf'), array))
6.0
The easiest way to do this is to use numpy.ma.masked_invalid():
a = numpy.log(numpy.arange(15))
a.sum()
# -inf
numpy.ma.masked_invalid(a).sum()
# 25.19122118273868
maybe you can index your matrix and use:
import numpy as np;
matrix = np.array([[1.,2.,3.,np.Inf],[4.,5.,6.,np.Inf],[7.,8.,9.,np.Inf]]);
print matrix[:,1];
print sum(filter(lambda x: x != np.Inf,matrix[:,1]));
print matrix[1,:];
print sum(filter(lambda x: x != np.Inf,matrix[1,:]));
Use masked arrays:
>>> 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