简体   繁体   中英

Applying a function element-wise to multiple numpy arrays

Say I have two numpy arrays of the same dimensions, eg:

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM