Search code examples
pythonnumpydivide-by-zero

Make division by zero equal to zero in a list


I have a list L and I want to compute for each elementconst/L_j and get a new list M with elements M_j = const/L_j. However, there are L_j elements that are zero. In this case it is preferred to assign such division to zero. I have made this the script below but it is slow.

temp = np.zeros((self.n_features, 1))
for t in range(self.n_features):
    if y[t]!=0:
        temp[t] = x/y[t] 

My question is similar to this but I want to apply it in a list. Is these a faster way to compute list M.

Thanks.


Solution

  • Assuming that your array is called L, you could do something like

    M = x/L
    M[np.isinf(M)] = 0
    

    The additional time required to zero out the bad elements is negligible, even when the number of infinites is large:

    In [20]: L = np.random.randint(0, 2, 100000)
    
    In [21]: %timeit [0 if l == 0 else 10/l for l in L]
    34.9 ms ± 2.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
    
    In [23]: %timeit M = 10/L
    263 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [24]: %timeit M[np.isinf(M)] = 0
    983 ns ± 40.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)