codeKiller
codeKiller

Reputation: 5739

How to handle ZeroDivisionError inside numpy array

I have two big numpy arrays, I need to divide them.

Since I am working on Python 32-bits, and the arrays are too big, to avoid FloatingPointError, I am doing, for example:

x = numpy.array([...],dtype=object)
y = numpy.array([...].dtype=object)

The problem is that, inside the array y, some elements can be 0.0

So, my question, how to handle the calculation x/y and avoid ZeroDivisionError.

For exmaple, I would like to force nan if the element in y is 0. So that, for that particular element inside the array, the calculation x/y=nan

Upvotes: 2

Views: 2219

Answers (2)

rth
rth

Reputation: 11201

Use masked arrays,

x = numpy.array([...],dtype=object)
y = numpy.array([...].dtype=object)

x_m = numpy.ma.array(x, mask=(x==0))
y_m = numpy.ma.array(y, mask=(y==0))

print(x_m/y_m)

Upvotes: 1

farhawa
farhawa

Reputation: 10398

Change dtype = object by dtype = float so division by zero will not throw runtime error but it will be considered as inf and than change inf by zeros.

a = np.array([1,2,3], dtype='float')
b = np.array([0,1,3], dtype='float')
c = a / b
c
array([ inf,   2.,   1.])
c[c == np.inf] = 0
c
array([ 0.,  2.,  1.])

Upvotes: 1

Related Questions