5

I use NumPy.

I have defined a vector x with NumPy and other variables with numerical values.

I will return a vector y of same length as x but the values y[i] in this vector y need to be computed from different formulas depending on the corresponding x[i].

Can I with NumPy do something smart or do I have to iterate through the vector x and for each element in x determine if x[i] is either greater than or less than a specific value and determine which formula to use for the specific element?

I guess I could do something like

y[x > a] = 2*x+7
y[x <= a] = 3*x+9
return y

1 Answer 1

6

Check out np.where http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html.

y = np.where(x > a, 2 * x + 7, 3 * x + 9)
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.