1

I have a vector D of length N and a matrix A of shape N*M. Vector D has some zero elements. I'm doing this operation:

D = D.reshape(-1,1)
A / D

However I'm getting a division by zero error because of some elements in D that are zero. What I need is to put zero when there's a division by zero instead of raising an error. How to do this?

E.g. my try:

A = [ [0,1,0,0,0,0], 
          [0,0,1,1,0,0],
          [1,0,0,1,1,0],
          [0,0,0,0,1,0],
          [0,0,0,0,0,0],
          [0,0,0,0,1,0] 
          ]
A = np.array(A, dtype='float')

D = np.sum(A, axis=1)
D = D.reshape(-1, 1)

A = np.where(D != 0, A / D, 0)

RuntimeWarning: invalid value encountered in divide
  A = np.where(D != 0, A / D, 0)
Jack Twain
  • 5,655
  • 10
  • 56
  • 100
  • 1
    That's a warning, not an error. You can safely ignore it in this case. As far as I know, your current version is the best solution. See similar discussions here: http://stackoverflow.com/a/13499499/553404 and http://stackoverflow.com/q/23129407/553404 – YXD May 07 '14 at 11:56
  • 1
    You can customize how errors are handled using the [`numpy.seterr`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html), however it doesn't provide a way to use a default value when an error is triggered. You can use the `call` mode and then a custom function will be called if an error is raised, however in order for the function to set the default value you'd have to manually pass a reference to the array and somehow tell the function where the error occurred. In other words, it doesn't ease your use-case. – Bakuriu May 07 '14 at 12:00
  • @AlexTwain did you try the approach proposed in the answer below? – Saullo G. P. Castro May 24 '14 at 06:01
  • related [Efficient element-wise matrix division when elements in denominator may be zero](http://stackoverflow.com/questions/23041434/efficient-element-wise-matrix-division-when-elements-in-denominator-may-be-zero) – TooTone Aug 10 '14 at 12:30
  • possible duplicate of [Divide one numpy array by another only where both arrays are non-zero](http://stackoverflow.com/questions/20293614/divide-one-numpy-array-by-another-only-where-both-arrays-are-non-zero) – mtrw Aug 10 '14 at 12:31

2 Answers2

1

You could use a masked array for D, like:

D = np.ma.array(D, mask=(D==0))

and when you perform the calculations with the masked array only the non-masked values will be considered.

Saullo G. P. Castro
  • 49,101
  • 22
  • 160
  • 223
  • @moarningsun thank you... you are right! I wrote using `nan_to_num()` because `0/0` was giving `nan`, but I agree with your comment. I've updated the answer with what I think is a more robust approach... – Saullo G. P. Castro Aug 10 '14 at 12:21
  • 1
    Oh `0/0` doesn't give `inf` (or `-inf`), I missed that! –  Aug 10 '14 at 12:29
0

Why not use try-catch block? Something like

try: some_var = A/D except ZeroDivisionError: some_var = 0

Alissa
  • 596
  • 1
  • 6
  • 20