Jack Twain
Jack Twain

Reputation: 6372

Replacing a division by zero error with a zero in numpy

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)

Upvotes: 1

Views: 2870

Answers (2)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58865

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.

Upvotes: 1

Alissa
Alissa

Reputation: 714

Why not use try-catch block? Something like

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

Upvotes: 0

Related Questions