Can this code with NumPy calculations be more efficient?

Viewed 54

I want to convert array a to log_e. If the number to be converted is non-positive, then convert it to 0:

import numpy as np
a = np.array([-1,0,1,2])
b = np.zeros(len(a))
for i in range(0,len(a)):
    if a[i] <= 0:
        b[i] = 0
    else:
        b[i] = np.log(a[i])

To improve the computing performance, I think the following is better. But then the error RuntimeWarning: divide by zero encountered in log pops out. Can I use some code to carry on with my expected calculations?

import numpy as np
a = np.array([0,0,1,2])
b = np.log(a)
2 Answers

use np.where on a to mask non-positive number with 1, then np.log:

b = np.log(np.where(a>0, a, 1))

Output:

array([0.        , 0.        , 0.        , 0.69314718])

As a "ufunc", numpy.log accepts the parameters where and out. So an efficient method for your computation is as follows.

In [6]: a = np.array([-1, 0, 1, 2])

Create the output array.

In [7]: b = np.zeros(len(a))

Tell numpy.log to only compute the result where a > 0, and put the output in b. This returns the array given as out, and modifies out (i.e. b) in-place.

In [8]: np.log(a, where=a > 0, out=b)
Out[8]: array([0.        , 0.        , 0.        , 0.69314718])

In [9]: b
Out[9]: array([0.        , 0.        , 0.        , 0.69314718])
Related