August 6th, 2013, 09:00 AM
Numpy: array division but only for non-zero values
I am using numpy n-dimensional arrays for some image processing and one thing I am doing is dividing element by element between two arrays.
So the code looks something like this:
where cc_num and cc_den are numpy arrays. The problem is some of the values in the cc_den can be 0 and I do not want to perform the division operation on those array elements.
import numpy as np
value = np.sum(np.absolute(cc_num/cc_den))
What is the pythonisque way to achieve this? Any help would be greatly appreciated.
August 6th, 2013, 09:20 AM
I found the solution. It is as follows:
nonzero = cc_den > 0
value = np.sum(np.absolute(cc_num[nonzero]/cc_den[nonzero]))