Replace division by zero numpy

I am making a matrix by stream division of the matrix, however there are some zeros in the divisor matrix. This leads to a warning in some NaNs. I want them to display at 0, which I can do as follows:

edge_map = (xy/(x_norm*y_norm)) edge_map[np.isnan(edge_map)] = 0 

However, there are two problems with this: first of all, this is a warning (I don’t like warnings), and secondly, this requires a second pass through the matrix (not sure if this is inevitable), and efficiency is very important for this part of the code. Ideas?

+6
source share
1 answer

This is probably the fastest solution, but the where function throws an error because it pre-computes the solutions:

 import numpy as np n = 4 xy = np.random.randint(4, size=(n,n)).astype(float) x_norm = np.random.randint(4, size=(n,n)).astype(float) y_norm = np.random.randint(4, size=(n,n)).astype(float) xy_norm = x_norm*y_norm edge_map = np.where(xy_norm == 0, xy_norm, xy/xy_norm) print(xy) print(xy_norm) print(edge_map) 
+4
source

All Articles