Ignoring -Inf values in arrays using numpy/scipy in Python

前端 未结 5 509
说谎
说谎 2020-12-25 14:11

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

相关标签:
5条回答
  • 2020-12-25 14:33

    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
    
    0 讨论(0)
  • 2020-12-25 14:33

    Use a filter():

    >>> array
    array([  1.,   2.,   3., -Inf])
    >>> sum(filter(lambda x: x != float('-inf'), array))
    6.0
    
    0 讨论(0)
  • 2020-12-25 14:36

    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
    
    0 讨论(0)
  • 2020-12-25 14:37

    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,:]));
    
    0 讨论(0)
  • 2020-12-25 14:46

    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
    
    0 讨论(0)
提交回复
热议问题