2

I have a Numpy array with positive and negative values. I need to apply a function to the positive numbers or zero (funcPos) and a different one to the negative numbers (funcNeg), getting the result as another array.

I know there is the numpy.where function, so I could do:

y = np.where(x >= 0, funcPos(x), funcNeg(x))

However, this applies funcPos and funcNeg to all the elements of the input array, trowing many errors in the process because those functions are not designed to deal with numbers of the wrong sign.

Do you have any suggestion on how to do this in a fast way (not using a loop)?

Many thanks,

1
  • 1
    You could call funcPos and funcNeg with a subset of x, and then combine the results? Commented Jul 21, 2017 at 13:18

1 Answer 1

5

I'd suggest the following:

y = np.zeros(x.shape) y[x >= 0.] = funcPos(x[x >= 0.]) y[x < 0.] = funcNeg(x[x < 0.])

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.