0

Hello I am wondering if I could use something like "try-except" to avoid error warnings and put np.nan in the result array?

for example

import numpy as np
a = np.array([1,1])
b = np.array([1,0])
c = a/b

there will be a "division by zero error" I wish to neglect this error and get c as np.array([1,np.nan])

I know I could use a loop and try-except to achieve this by iterate through all elements in the array. However, is there a more elegant way to do this with out a loop?

If it has to be a loop, what would be the fastest way to do?

1

1 Answer 1

0
In [219]: a = np.array([1,1]) 
     ...: b = np.array([1,0]) 
     ...: c = a/b                                                                              
/usr/local/bin/ipython3:3: RuntimeWarning: divide by zero encountered in true_divide
  # -*- coding: utf-8 -*-
In [220]: c                                                                                    
Out[220]: array([ 1., inf])

Replace the / with divide. As a ufunc it accepts where and out parameters, which work together to skip the 0's and place a nan instead:

In [224]: np.divide(a,b, where=(b!=0), out=np.full(a.shape,np.nan))                            
Out[224]: array([ 1., nan])

It is also possible to suppress the warning, but that doesn't replace the inf with nan. This ufunc code is the simplest way to do both.

Applying a function across a numpy array gives different answers in different runs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.