0

In Python I have a Matrix with some zero values, how can I apply a natural logarithm and obtain zero for when the matrix entry is zero? I am using numpy.log(matrix) to apply the natural logarithm function, but I am getting nan when the matrix entry is equal to zero, and I would like it to be zero instead

hpaulj
  • 221,503
  • 14
  • 230
  • 353
DiegoA86
  • 1
  • 3

4 Answers4

1

You can do something like this:

arr = numpy.nan_to_num(numpy.log(matrix))

The behavior of nan_to_num replaces all the NaNs by zeroes.

You can find more information here:

Another alternative is to pass a mask to the where= argument of the np.log function.

Rayan Hatout
  • 640
  • 5
  • 22
0

You can use np.where. The seterr is to turn off the warning.

RuntimeWarning: divide by zero encountered in log

In:

np.seterr(divide = 'ignore')

matrix = np.array([[10,0,5], [0,10,12]])
np.where(matrix == 0, 0, np.log(matrix))

Out:

array([[2.30258509, 0.        , 1.60943791],
       [0.        , 2.30258509, 2.48490665]])
Michael Gardner
  • 1,693
  • 1
  • 11
  • 13
0

You can use numpy.log1p it will evaluate to zero if the entry is zero (since the Log of 1 is zero) and the reverse operation is numpy.expm1.

You can find more information in the documentation:

  1. Log1p
  2. Expm1
Milton Arango G
  • 775
  • 9
  • 16
0

np.log is a ufunc that takes a where parameter. That tells it which elements of x will be used in the calculation. The rest are skipped. This is best used with a out parameter, as follows:

In [25]: x = np.array([1.,2,0,3,10,0])                                          
In [26]: res = np.zeros_like(x)                                                 
In [27]: idx = x>0                                                              
In [28]: np.log(x)                                                              
/usr/local/bin/ipython3:1: RuntimeWarning: divide by zero encountered in log
  #!/usr/bin/python3
Out[28]: 
array([0.        , 0.69314718,       -inf, 1.09861229, 2.30258509,
             -inf])
In [29]: np.log(x, out=res, where=idx)                                          
Out[29]: 
array([0.        , 0.69314718, 0.        , 1.09861229, 2.30258509,
       0.        ])
hpaulj
  • 221,503
  • 14
  • 230
  • 353