如果我有一个像func(x,y)= cos(x)+ sen(y)+ x * y这样的随机函数,如何将其应用于2个数组中的所有元素对?
If I have a random function like func(x,y) = cos(x) + sen(y) + x*y how can I apply it to all the pairs of elements in 2 arrays?
我找到了 docs.scipy /doc/numpy/reference/generation/numpy.outer.html 和 发现所有基本操作都有外部功能.但是,如果我想使用自定义功能怎么办?
I found docs.scipy/doc/numpy/reference/generated/numpy.outer.html and discovered that there are outer functions for all the basic operations. But what if I want to do it with a custom function?
想象array1为[1,2],array2为[3,4],我想应用的函数称为f(float,float)
Imagine array1 is [1,2], array2 is [3,4] and the function I wanted to apply is called f(float, float)
预期输出为
[f(1,3)f(1,4)
[f(1,3) f(1,4)
f(2,3)f(2,4)]
f(2,3) f(2,4)]
推荐答案只要确保以正确广播的方式编写函数,就可以做到
As long as you make sure to write your function in such a way that it broadcasts properly, you can do
f(x_arr[:, None], y_arr)将其应用于两个一维数组x_arr和y_arr中的所有元素对.
to apply it to all pairs of elements in two 1-dimensional arrays x_arr and y_arr.
例如,要以广播方式编写示例函数,请将其编写为
For example, to write your example function in a way that broadcasts, you'd write it as
def func(x, y): return np.cos(x) + np.sin(y) + x*y由于np.cos,np.sin,+和*在整个阵列中广播和矢量化.
since np.cos, np.sin, +, and * broadcast and vectorize across arrays.
至于它是否不广播?好吧,有些人可能会建议np.vectorize,但是您要记住很多棘手的事情,例如保持一致的输出dtype且没有副作用.如果您的函数没有广播,我建议您仅使用列表推导:
As for if it doesn't broadcast? Well, some might suggest np.vectorize, but that has a lot of tricky things you have to keep in mind, like maintaining a consistent output dtype and not having side effects. If your function doesn't broadcast, I'd recommend just using list comprehensions:
np.array([[f(xval, yval) for yval in y_arr] for xval in x_arr])更多推荐
如何在python中计算外部函数?
发布评论