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

前端 未结 5 554
说谎
说谎 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
    

提交回复
热议问题