0

I have a function that takes two numpy arrays as an argument, and I need to perform some basic checks on the elements of the array inside the function. Something like this:

import numpy as np

xdata = np.arange(0,10)
ydata = np.arange(0,100,10)

def div(x, y):
#   if y == 0:
#       return 0
    return x/y

zdata = div(xdata, ydata)

I understand why the commented lines cause an error, but I don't know if there is a simple way to make them work.

I am using an external module that calls this function, so the data checking has to be inside the function and the type must be a numpy array. A grossly simplified version:

def div(x, y):
    return x/y

foo.set_function(div)
z = foo.bar()

# In external module
class foo:

    def set_function(f):
        self.func = f

    def bar():
        x = np.ndarray()
        y = np.ndarray()
        return self.f(x, y)

Thanks in advance!

iain
  • 21
  • 3
  • So the problem is that you don't know how to set the undefined elements of the division to zero? In the top code, you are setting the whole array to zero, is that you want? Or just the elements that are not defined? Please give a proper example of the expected output. – anishtain4 Feb 04 '20 at 15:04
  • So I don't want to set the whole array to zero, I just want to avoid the case of a divide by zero error for a single element. I'm actually trying to do something more complex, but this is a simple example of wanting to manipulate the elements of the array inside the function. – iain Feb 04 '20 at 15:11
  • You can let numpy do the zero division, and then find those elements using `np.isnan()` to find and modify them to whatever you want. Something like: `ans = x/y; ind = np.isnan(ans); and[ind]=0` – anishtain4 Feb 04 '20 at 15:13
  • You can use answers from [How to return 0 with divide by zero](https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero) which handles numpy array with zero divisors. – DarrylG Feb 04 '20 at 15:27
  • I found the where= optional argument in the numpy functions in the link DarryIG provided was able to solve my problem. Thanks all. – iain Feb 04 '20 at 15:47
  • Can you explain what you're actually trying to do? This reads like a case of the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. – AMC Feb 04 '20 at 23:58

0 Answers0