numpy: Efficiently avoid 0s when taking log(matrix)

前端 未结 7 631
陌清茗
陌清茗 2020-12-13 18:12
from numpy import *

m = array([[1,0],
           [2,3]])

I would like to compute the element-wise log2(m), but only in the places whe

相关标签:
7条回答
  • 2020-12-13 18:53

    The masked array solution and the solution that disables the warning are both fine. For variety, here's another that uses scipy.special.xlogy. np.sign(m) is given as the x argument, so xlogy returns 0 wherever np.sign(m) is 0. The result is divided by np.log(2) to give the base-2 logarithm.

    In [4]: from scipy.special import xlogy
    
    In [5]: m = np.array([[1, 0], [2, 3]])
    
    In [6]: xlogy(np.sign(m), m) / np.log(2)
    Out[6]: 
    array([[ 0.       ,  0.       ],
           [ 1.       ,  1.5849625]])
    
    0 讨论(0)
提交回复
热议问题