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

前端 未结 7 665
陌清茗
陌清茗 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:41

    Another option is to use the where parameter of numpy's ufuncs:

    m = np.array([[1., 0], [2, 3]])
    res = np.log2(m, out=np.zeros_like(m), where=(m!=0))
    

    No RuntimeWarning is raised, and zeros are introduced where the log is not computed.

提交回复
热议问题