1

Say I have two numpy arrays of the same dimensions, e.g.:

a = np.ones((4,))
b = np.linspace(0,4,4)

and a function that is supposed to operate on elements of those arrays:

def my_func (x,y):
   # do something, e.g.
   z = x+y
   return z

How can I apply this function to the elements of a and b in an element-wise fashion and get the result back?

2
  • You need to provide more data about your function. As is the answer is trivially a+b. Commented Apr 3, 2014 at 19:35
  • Or trivially my_func(a,b). Commented Apr 3, 2014 at 19:35

1 Answer 1

1

It depends, really. For the given function; how about 'a+b', for instance? Presumably you have something more complex in mind though.

The most general solution is np.vectorize; but its also the slowest. Depending on what you want to do, more clever solutions may exist though. Take a look at numexp for example.

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.