简体   繁体   English

将功能元素应用于多个numpy数组

[英]Applying a function element-wise to multiple numpy arrays

Say I have two numpy arrays of the same dimensions, eg: 说我有两个相同尺寸的numpy数组,例如:

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? 如何以元素为单位将此函数应用于ab的元素并返回结果?

It depends, really. 这取决于,真的。 For the given function; 对于给定的功能; how about 'a+b', for instance? 例如,“ a + b”怎么样? Presumably you have something more complex in mind though. 大概您在想些复杂的事情。

The most general solution is np.vectorize; 最通用的解决方案是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. 以numexp为例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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