14

I have a definition

def myfunc(a, b):
    if a < (b*10):
        result = a*2
    else:
        result = a*(-1)
    return result

Now this obviously works perfectly when I feed in my a and b values one by one using for loops, however it takes forever (I've simplified the definition a wee bit) and I know from experience that passing in the values as an array will speed it up.

So how do I modify this code to accept arrays. I've used the any() and all() commands but I must be using them wrong as my function only spits out one value rather than an array of values.

An example of my desired output would be:

>>>a = np.array([1,5,50,500])
>>>b = 1
>>>print myfunc(a, b)
array([-1, -5, 100, 1000])

3 Answers 3

18

You could use np.where:

def myfunc(a, b):
    return np.where(a < b*10, a*2, -a)    

For example,

In [48]: a = np.array([1, 5, 50, 500])

In [49]: b = 1

In [50]: myfunc(a, b)
Out[50]: array([   2,   10,  -50, -500])

Note the output is not the same as your desired output, but is consistent with the code you posted. You can of course get the desired output by reversing the inequality:

def myfunc(a, b):
    return np.where(a > b*10, a*2, -a)

then

In [52]: myfunc(a, b)
Out[52]: array([  -1,   -5,  100, 1000])
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much! Although this does work, there was another comment that simply used np.all(a < (b*10)) with my existing definition; why should I use np.where instead of np.all?...edit-ooops it seems I did put the inequality the wrong way around, fortunately this didn't create confusion to my question :)
np.all returns a single boolean value, True or False. It simply tests if each and every element of a (and corresponding element of b) satisfies a < b*10. (It returns True if the condition is true element-wise, otherwise it returns False). I don't think that helps you in this situation.
Great answer! I wasn't aware you can use np.where with the additional two arguments, I will definitely be using this much more often
0

Use a list comprehension:

myarray = [1, 5, 50, 500]
b = 1
[myfunc(a, b) for a in myarray]

Comments

0

Your function is simple enough that it can be dropped entirely:

arr = [1, 5, 50, 500]
arr = [a * 2 if a < b * 10 else -a for a in arr]

2 Comments

But I expect the list comp to be significantly slower than the numpy array operations.
@mgilson: Absolutely. I just have no numpy experience

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.